更改Python中Tkinter Button的命令方法

Cri*_*ian 8 python user-interface tkinter

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

akd*_*dom 24

虽然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()
Run Code Online (Sandbox Code Playgroud)

如果你只使用鼠标,¹"很好"; 如果你关心标签并在按钮上使用[Space]或[Enter],那么你也必须实现(复制现有代码)按键事件.command通过设置选项.configure要容易得多.

²实例化后唯一不能改变的属性是name.