我创建了一个新的Button对象,但在创建时没有指定command
选项。在创建对象后,Tkinter中是否有一种方法可以更改命令(onclick)功能?
答案 0 :(得分:21)
虽然Eli Courtwright's程序可以正常工作¹但是你真正想要的只是一种在实例化后重新配置你在实例化时可以设置的任何属性的方法。你如何这样做是通过configure()方法。
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()
如果你只使用鼠标,那么¹“很好”;如果你关心标签并在按钮上使用[Space]或[Enter],那么你也必须实现(复制现有代码)按键事件。通过command
设置.configure
选项要容易得多。
²实例化后唯一无法更改的属性是name
。
答案 1 :(得分:1)
不确定;只需使用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()