Change Method command for Tkinter button in Python

I create a new Button object, but did not specify a parameter when I created it command. Is there a way in Tkinter to change the command (onclick) after the object has been created?

+5
source share
2 answers

Although the Eli Courtwright program will work fine¹ , what you really want is just a way to reconfigure after creating an instance any attribute that you could set when creating the instance², How do you do this using 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()

¹ "", ; [] [] , ( ) . command .configure .

² , , name.

+15

; bind, . . 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()
+1

All Articles