I use tkinter on python 2.7. My problem is that I don't succeed in getting the variable entered into the entry_number; the function is called, but it didn't print anything.
How can I know if the checkbox is checked or not?
from tkinter import *
from tkinter import Tk, StringVar, Label, Entry, Button
def call():
print (e)
root = Tk()
var1 = IntVar()
c=Checkbutton(root, text="Bou ", variable=var1).grid(row=4, column=1)
text = StringVar(root)
button = Button(root, text='call',
command=call)
entry_number = Entry(root)
button.grid(column=8, row=20)
entry_number.grid(column=6,row=4)
e = entry_number.get()
root.mainloop()
The problem is that you define e immediately when you are creating the UI. At this point, the entry is still empty, so all that is printed when you press the button is an empty string.
Instead, put the definition of e inside the function, so it is updated each time you click:
def call():
e = entry_number.get()
print (e)
Related
I want to write a program where after a user enters text and clicks a button, the text becomes a label and the button text is changed. My code is:
# Imports
import os, sys
import tkinter
"""
Tkinter program 1
text box + button + label
"""
# Button Entry
def enter(inputtedinfo, randvar, EnterMessage):
randvar = inputtedinfo.get()
EnterMessage = "Submitted!"
# Main Function
def main():
something = tkinter.Tk()
something.title("My First Tkinter Window")
something.geometry("600x400")
randvar = ""
EnterMessage = "Enter"
inputtedinfo = tkinter.StringVar()
userLabel = tkinter.Label(something, text = randvar)
userEntry = tkinter.Entry(something, textvariable = inputtedinfo)
userButton = tkinter.Button(something, text = EnterMessage, command = enter(inputtedinfo, randvar, EnterMessage))
userEntry.grid(row=0,column=0)
userLabel.grid(row=0,column=1)
userButton.grid(row=0,column=2)
something.mainloop()
sys.exit(0)
if(__name__ == "__main__"):
main()
The user input works, but clicking the button does nothing despite the fact that it is supposed to change the variables for the button and label displays. Did I mess up somewhere?
The command argument takes the name of a function. If you write the complete call with arguments, it's not the name of the function but whatever is returned by this exact function call. So, your button will not work. It will have the command None.
In order to do what you want to do, you have to make the StringVar()s accessible to the function you are calling. So, you can both get the contents of the entry and change the values of the button and the label. To do this, best add the string variables and the widgets as attributes to the toplevel you already created (something). So, they stay available to all functions and you can get and change information:
# Button Entry
def enter():
something.randvar.set(something.inputtedinfo.get())
something.userButton["text"] = "Submitted!"
# Main Function
def main():
global something
something = tkinter.Tk()
something.title("My First Tkinter Window")
something.geometry("600x400")
something.randvar = tkinter.StringVar()
something.randvar.set("")
EnterMessage = "Enter"
something.inputtedinfo = tkinter.StringVar()
userLabel = tkinter.Label(something, textvariable = something.randvar)
something.userEntry = tkinter.Entry(something, textvariable = something.inputtedinfo)
something.userButton = tkinter.Button(something, text = EnterMessage, command = enter)
something.userEntry.grid(row=0,column=0)
userLabel.grid(row=0,column=1)
something.userButton.grid(row=0,column=2)
something.mainloop()
if(__name__ == "__main__"):
main()
There are few issues in your code:
assign string to textvariable, should use StringVar instead
command=enter(...) will execute enter(...) immediately and then assign None to command option, should use lambda instead
updating strings inside enter() does not automatically update the label and the button, should use .set() on the StirngVar instead
Below is modified code:
def enter(inputtedinfo, randvar, EnterMessage):
# used .set() to update StringVar
randvar.set(inputtedinfo.get())
EnterMessage.set("Submitted!")
def main():
something = tkinter.Tk()
something.title("My First Tkinter Window")
something.geometry("600x400")
randvar = tkinter.StringVar() # changed to StringVar()
EnterMessage = tkinter.StringVar(value="Enter") # changed to StringVar()
inputtedinfo = tkinter.StringVar()
userLabel = tkinter.Label(something, textvariable=randvar) # used textvariable instead of text option
userEntry = tkinter.Entry(something, textvariable=inputtedinfo)
userButton = tkinter.Button(something, textvariable=EnterMessage, command=lambda: enter(inputtedinfo, randvar, EnterMessage))
userEntry.grid(row=0,column=0)
userLabel.grid(row=0,column=1)
userButton.grid(row=0,column=2)
something.mainloop()
from Tkinter import *
import ttk
main=Tk()
def print1(event):
string = ""
string = combobox1.get()
print combobox1.get()
val = StringVar()
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.bind("<Key>", print1)
combobox1.focus_set()
combobox1.pack()
mainloop()
How can I fix the problem that is, when I press the first button, it didn't show immediately.
For example, when I pressed a, it didn't show anything, and then I pressed b. It will show a, but not ab.
How can I fix this bug?
thanks.
You have it very close. The bind statement is slightly different from what you need. The problem was that it was printing before the key was delivered to the combobox. Now it waits until the key is released to fire the event.
from Tkinter import *
import ttk
main=Tk()
def print1(event):
string = ""
string = combobox1.get()
print combobox1.get()
val = StringVar()
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.bind("<KeyRelease>", print1)
combobox1.focus_set()
combobox1.pack()
mainloop()
#Ron Norris seems to figured-out and solved your issue. Regardless, here's another way to do things that doesn't involve binding events, it uses the trace() method common to all Tkinter variable classes (BooleanVar, DoubleVar, IntVar, and StringVar) which is described here. The arguments it receives when called are explained in the answer to this question.
from Tkinter import *
import ttk
main=Tk()
def print1(*args):
string = combobox1.get()
print string
val = StringVar()
val.trace("w", print1) # set callback to be invoked whenever variable is written
combobox1 = ttk.Combobox(main, textvariable=val, height=4)
combobox1.focus_set()
combobox1.pack()
mainloop()
From the first answer here:
StackOverflow #6548837
I can call callback when the user is typing:
from Tkinter import *
def callback(sv):
print sv.get()
root = Tk()
sv = StringVar()
sv.trace("w", lambda name, index, mode, sv=sv: callback(sv))
e = Entry(root, textvariable=sv)
e.pack()
root.mainloop()
However, the event occurs on every typed character. How to call the event when the user is done with typing and presses enter, or the Entry widget loses focus (i.e. the user clicks somewhere else)?
I think this does what you're looking for. I found relevant information here. The bind method is the key.
from Tkinter import *
def callback(sv):
print sv.get()
root = Tk()
sv = StringVar()
e = Entry(root, textvariable=sv)
e.bind('<Return>', (lambda _: callback(e)))
e.pack()
root.mainloop()
To catch Return key press event, the standard Tkinter functionnality does it. There is no need to use a StringVar.
def callback(event):
pass #do the work
e = Entry(root)
e.bind ("<Return">,callback)
I'm trying to use Tkinter's Entry widget. I can't get it to do something very basic: return the entered value. Does anyone have any idea why such a simple script would not return anything? I've tried tons of combinations and looked at different ideas.
This script runs but does not print the entry:
from Tkinter import *
root = Tk()
E1 = Entry(root)
E1.pack()
entry = E1.get()
root.mainloop()
print "Entered text:", entry
Seems so simple.
Edit
In case anyone else comes across this problem and doesn't understand, here is what ended up working for me. I added a button to the entry window. The button's command closes the window and does the get() function:
from Tkinter import *
def close_window():
global entry
entry = E.get()
root.destroy()
root = Tk()
E = tk.Entry(root)
E.pack(anchor = CENTER)
B = Button(root, text = "OK", command = close_window)
B.pack(anchor = S)
root.mainloop()
And that returned the desired value.
Your first problem is that the call to get in entry = E1.get() happens even before your program starts, so clearly entry will point to some empty string.
Your eventual second problem is that the text would anyhow be printed only after the mainloop finishes, i.e. you close the tkinter application.
If you want to print the contents of your Entry widget while your program is running, you need to schedule a callback. For example, you can listen to the pressing of the <Return> key as follows
import Tkinter as tk
def on_change(e):
print e.widget.get()
root = tk.Tk()
e = tk.Entry(root)
e.pack()
# Calling on_change when you press the return key
e.bind("<Return>", on_change)
root.mainloop()
from tkinter import *
import tkinter as tk
root =tk.Tk()
mystring =tk.StringVar(root)
def getvalue():
print(mystring.get())
e1 = Entry(root,textvariable = mystring,width=100,fg="blue",bd=3,selectbackground='violet').pack()
button1 = tk.Button(root,
text='Submit',
fg='White',
bg= 'dark green',height = 1, width = 10,command=getvalue).pack()
root.mainloop()
I am new to Tkinter and not to sure how to proceed. I am trying to link a function that I define to a entry widget that is activated by a button. but I can't figure out how to get the three to communicate to each other. I would like it to print as well as return to the script so that I can be used in another function. This is what I have so far:
import Tkinter as tk
def TestMath(x):
calculate = x + 4
print calculate
return calculate
root = tk.Tk()
entry = tk.Entry(root)
value = entry.get()
number = int(value)
button = tk.Button(root, text="Calculate")
calculation = TestMath(number)
root.mainloop()
Button calls function assigned to command= (it has to be "function name" without () and arguments - or lambda function)
TestMath assigns calculation to global variable result and other functions can have access to that value.
import Tkinter as tk
def TestMath():
global result # to return calculation
result = int(entry.get())
result += 4
print result
result = 0
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
button = tk.Button(root, text="Calculate", command=TestMath)
button.pack()
root.mainloop()
Function called by button don't have to return value because there is no object which could receive that value.