Change command Method for Tkinter Button in Python
Asked Answered
A

3

20

I create a new Button object but did not specify the command option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?

Archibold answered 16/9, 2008 at 0:48 Comment(0)
P
39

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.

Pisistratus answered 16/9, 2008 at 1:24 Comment(0)
S
4

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()
Seamanlike answered 16/9, 2008 at 1:12 Comment(2)
The command config option is what typically is used for button presses. The callback function does not need an event argument.Ane
Using a bind isn't a particularly good solution IMO. This is exactly what the -command option is for. Plus, by doing this in a binding you lose the ability to have the callback called via keyboard traversal unless you also add key bindings. It gets pretty messy pretty quick, so stick with -command.Bonsai
E
0

I was testing this and found this way:

buttonWidget.configure(command=yourCommand)
Etter answered 14/2 at 22:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.