Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

user interface - Change command Method for Tkinter Button in Python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Though Eli Courtwright's program will work fine1, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated2. How you do so is by way of the configure() method.

from Tkinter import Tk, Button

def goodbye_world():
    print "Goodbye World!
Wait, I changed my mind!"
    button.configure(text = "Hello World!", command=hello_world)

def hello_world():
    print "Hello World!
Wait, 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()

1 "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.

2 the only attribute that can't change after instantiation is name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...