在Python中更改Tkinter Button的命令方法

时间:2020-03-05 18:54:53  来源:igfitidea点击:

我创建了一个新的Button对象,但在创建时未指定command选项。创建对象后,Tkinter中是否可以更改命令(onclick)功能?

解决方案

回答

当然;只需在创建按钮之后使用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()

回答

尽管Eli Courtwright的程序可以正常运行1,但是我们似乎真正想要的只是在实例化之后重新配置实例化时可以设置的任何属性的一种方法。这样做是通过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()

如果仅使用鼠标,则为1"精";否则为1. 如果我们关心使用制表符并使用按钮上的[Space]或者[Enter],那么我们也将必须实现(复制现有代码)按键事件。通过.configure设置command选项要容易得多。

2实例化后唯一不变的属性是name