问题描述
我正在尝试在实例化后设置或更新 OptionMenu 的命令.
I am trying to set or update the command of an OptionMenu after its instantiation.
widget.configure(command=foo)
语句适用于 Button
和 CheckButton
,但不适用于 OptionMenu
.
The widget.configure(command=foo)
statement works for Button
and CheckButton
, but not for OptionMenu
.
以下代码引发此错误:_tkinter.TclError: unknown option "-command"
from Tkinter import Tk, OptionMenu, StringVar
root = Tk()
var = StringVar()
def foo(val):
print val, var.get()
widget = OptionMenu(root, var, "one", 'two')
widget.configure(command=foo)
widget.pack()
root.mainloop()
推荐答案
我认为您真正要问的是如何将命令与 Optionmenu
相关联,而不是 update 一个命令(没有命令,所以没有什么要更新的).
I think what you're really asking is how to associate a command to an Optionmenu
, rather than update a command (there is no command, so there's nothing to update).
如果您希望每次从 Optionmenu
中选择一个值时都调用一个函数,您可以在相关变量上添加跟踪.无论是通过 Optionmenu
还是任何其他方式,只要该变量发生变化,跟踪就会调用一个函数.
If you want a function to be called every time a value is selected from an Optionmenu
, you can add a trace on the related variable. The trace will call a function whenever that variable changes, whether through the Optionmenu
or any other means.
例如:
...
var = tk.StringVar()
def foo(*args):
print "the value changed...", var.get()
var.trace("w", foo)
...
当函数被调用时,它将传递三个参数,在这种情况下你可以安全地忽略它们.
When the function is called it will pass three arguments, which you can safely ignore in this case.
有关变量跟踪的更多信息,请参见 http://effbot.org/tkinterbook/variable.htm一个>
For more information on variable traces see http://effbot.org/tkinterbook/variable.htm
您可能还想考虑切换到 ttk 组合框.它支持绑定到 <<ComboboxSelected>>
,这比做一个变量跟踪要稍微简单一些.
You might also want to consider switching to the ttk combobox. It supports binding to <<ComboboxSelected>>
, which is every so slightly less clunky than doing a variable trace.
这篇关于如何更新 OptionMenu 的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!