Python Tkinter - Passing Values With A Button
Solution 1:
The other answers here work, but like a lot of things in life, there's more than one way to do what you're trying to do.
The code in your question actually mixes a couple of methods of getting data from the Entry widget. You're using textvariable and lambda, but you only need one. It seems like lambda has been covered, so here's a quick answer about textvariable:
First, you need to make your variable of a Tkinter string type like this:
variable = StringVar()
Your entry widget is fine, it's connected to the StringVar(). Your button doesn't need lambda, though, because you don't need to pass an argument to your RandomFunction().
FunctionCall = Button(MainWindow, text='Enter', command=RandomFunction).pack()
Lastly, your function needs a little rework, because it's not taking an argument anymore, it's just going to use the .get() method on your StringVar() whenever it's called:
def RandomFunction():
print(variable.get())
You can read more about StringVar()s here: http://effbot.org/tkinterbook/variable.htm
Solution 2:
You use .get() to get the contents of an Entry. From the effbot page http://effbot.org/tkinterbook/entry.htm
from Tkinter import *
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
def callback():
print e.get()
b = Button(master, text="get", width=10, command=callback)
b.pack()
master.mainloop()
Solution 3:
Using lambda
to create a function that calls the function with the argument is fine (as long as you do it correctly):
FunctionCall = Button(MainWindow, text="Enter", command=lambda: RandomFunction(EntryBox.get))
Python will be happy with this because the lambda
doesn't take any arguments.
Post a Comment for "Python Tkinter - Passing Values With A Button"