我创建了一个新的Button对象,但command在创建时没有指定该选项。在创建对象后,Tkinter中是否有一种方法可以更改命令(onclick)功能?
发布于 2018-09-25 09:32:46
虽然Eli Courtwright的程序运行良好¹,但你真正想要的只是一种在实例化后重新配置任何属性的方法,你可以在实例化时设置它。你是如何通过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。
发布于 2018-09-25 10:30:56
当然; 只需使用该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()
https://stackoverflow.com/questions/-100000792
复制相似问题