This can be done using a lambda, like so:
button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))
This is a simple way to bind the argument without an explicit wrapper method or modifying the original action.
This can be done using a lambda, like so:
button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))
This is a simple way to bind the argument without an explicit wrapper method or modifying the original action.
This can also be done by using partial from the standard library functools, like this:
from functools import partial
#(...)
action_with_arg = partial(action, arg)
button = Tk.Button(master=frame, text='press', command=action_with_arg)
[Tkinter] Button command is executed as soon as the program is run without pressing the button
user interface - Change command Method for Tkinter Button in Python - Stack Overflow
Python tkinter button: command calls function without being pressed
Tkinter button command using lambda to call a class method - how???
Videos
I'm trying to create a button that shows a label and entry widget when pressed. However, the button, label and entry widget all show up without the button even being pressed. The following is my code:
from tkinter import *
main = Tk()
main.title('Test')
lbl1 = Label(main, text= 'BUTTON PRESSED')
ent1= Entry(main)
def onclick():
lbl1.grid(row=1, column= 0, padx=35, pady=5)
ent1.grid(row=3,column=0)
btn1 = Button(main, text = 'Press to Begin', command= onclick())
btn1.grid(row=0, column=0, padx=30, pady=4)
main.mainloop()
Though Eli Courtwright's program will work fine¹, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated². How you do so is by way of the configure() method.
from Tkinter import Tk, Button
def goodbye_world():
print "Goodbye World!\nWait, I changed my mind!"
button.configure(text = "Hello World!", command=hello_world)
def hello_world():
print "Hello World!\nWait, I changed my mind!"
button.configure(text = "Goodbye World!", command=goodbye_world)
root = Tk()
button = Button(root, text="Hello World!", command=hello_world)
button.pack()
root.mainloop()
¹ "fine" if you use only the mouse; if you care about tabbing and using [Space] or [Enter] on buttons, then you will have to implement (duplicating existing code) keypress events too. Setting the command option through .configure is much easier.
² the only attribute that can't change after instantiation is name.
Sure; just use the bind method to specify the callback after the button has been created. I've just written and tested the example below. You can find a nice tutorial on doing this at http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
from Tkinter import Tk, Button
root = Tk()
button = Button(root, text="Click Me!")
button.pack()
def callback(event):
print "Hello World!"
button.bind("<Button-1>", callback)
root.mainloop()