更改Python中Tkinter Button的命令方法

时间:2008-09-16 00:48:37

标签: python user-interface tkinter

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

2 个答案:

答案 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()