当您在 Optionmenu() 小部件中声明“option2”时,它可以工作。更多示例可以阅读here和here。
from tkinter import *
main = Tk()
var = StringVar()
options = OptionMenu(main, var, 'option1', 'option2')
options.grid()
#options['menu'].add_command(label='option2')
main.mainloop()
我发现menu 选项用于在Menu() 小部件中创建项目,但不适用于Optionmenu() 小部件。这是here。您可以阅读有关如何声明 .Menu() 小部件 here 的更多信息。祝您的 tkinter 开发顺利。
编辑1:
失败的原因是您没有声明与.add_command 方法关联的command 选项。单独完成此操作后,您会注意到 Optionmenu 仍然没有使用添加的菜单项的新标签进行更新。要解决此问题,您必须使用控制变量StringVar 的.set() 方法进行更新。请参阅下面的修订脚本。
from tkinter import *
def _print1(value):
# By default, callback to OptionMenu has a positional argument for the
# menu item's label.
print(value)
print(var.get())
def _print2():
var.set('option2')
print(var.get())
main = Tk()
var = StringVar()
options = OptionMenu(main, var, 'option1',command=_print1)
options.grid()
options['menu'].add_command(label='option2', command=_print2)
# To add more clickable menu items, the 'add_command' method requires you to
# to declare it's options 'label' and 'command'.
main.mainloop()
编辑2:
- 备注,我已在 Edit1 中将
command 方面添加到options。一世
之前没有解决,但认为需要显示
完整性。
- 在您的 UPDATE 中回答您的问题,做您想做的事,我
将脚本重写为类对象。我也使用了内部类
_setit 在 tkinter 中找到,OptionMenu 小部件曾用于
配置command 使用的回调。这种方法克服了您遇到的问题。
修改后的代码:
from tkinter import *
class App(Tk):
def __init__(self, parent=None):
Tk.__init__(self, parent)
self.parent=parent
self.createOM()
self.grid()
def createOM(self):
# Create OptionMenu
omlist=['option1']
self.var = StringVar()
self.options = OptionMenu(self, self.var, *omlist,
command=self._print1)
self.options.grid()
values = ['hello', 'bob', 'testing']
for v in values:
self.options['menu'].add_command(
label=v, command=_setit(self.var, v, self._print2))
# To add more clickable menu items, the 'add_command' method requires you to
# to declare it's options 'label' and 'command'.
def _print1(self, value, *args):
#callback for OptionMenu has these arguments because inherently it
#uses the _setit class to configure the callback with these arguments.
print()
print(value)
#self.var.set('option10') #Uncomment to change OptionMenu display
print(self.var.get())
def _print2(self, value, *args):
print()
print(value)
#self.var.set('option20') #Uncomment to change OptionMenu display
print(self.var.get())
#The following class is extracted from tkinter.
class _setit:
"""Internal class. It wraps the command in the widget OptionMenu."""
def __init__(self, var, value, callback=None):
self.__value = value
self.__var = var
self.__callback = callback
def __call__(self, *args):
self.__var.set(self.__value)
if self.__callback:
self.__callback(self.__value, *args)
if __name__ == "__main__":
app = App()
app.mainloop()