本文介绍了在 Python 中更改 Tkinter 按钮的命令方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个新的 Button 对象,但在创建时没有指定 command 选项.Tkinter 有没有办法在创建对象后更改命令(onclick)函数?

I create a new Button object but did not specify the command option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?

推荐答案

虽然 Eli Courtwright 的 程序可以正常工作¹,您似乎真正想要的只是一种在实例化后重新配置您在实例化时可以设置的任何属性的方法².你如何做到这一点是通过 configure() 方法.

Though Eli Courtwright's program will work fine¹, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated². How you do so is by way of the configure() method.

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

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

¹ "fine" if you use only the mouse; if you care about tabbing and using [Space] or [Enter] on buttons, then you will have to implement (duplicating existing code) keypress events too. Setting the command option through .configure is much easier.

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

² the only attribute that can't change after instantiation is name.

这篇关于在 Python 中更改 Tkinter 按钮的命令方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:21