Tkinter 在初始化后更改哪个 StringVar 正在跟踪 OptionMenu

Tkinter change which StringVar is tracing an OptionMenu after initialization

我不知道如何将不同的 StringVar 分配给已经存在的 OptionMenu

例如:

def optionMenuChanged(*args):
    print(args[0]) # prints var1 if assigned to foo, prints var2 if assigned to bar
foo = tk.StringVar(name = 'var1')
foo.trace('w', optionMenuChanged)
bar = tk.StringVar(name = 'var2')
bar.trace('w', optionMenuChanged)
choices = ['1', '2', '3']
menu = OptionMenu(frame, foo, *choices)
'''
do stuff with menu
'''
menu.SetVariable(bar) # SetVariable does not exist
'''
do other stuff with menu
'''

这可能吗?

可以,但比较棘手。

  • 首先定义一个函数如下:
    def set_var(optmenu, var, callback=None):
        menu = optmenu['menu']
        last = menu.index('end')
        for i in range(last+1):
            label = menu.entrycget(i, 'label')
            menu.entryconfig(i, command=tk._setit(var, label, callback))
        optmenu.config(textvariable=var)
    
  • 然后每当你想改变变量时调用它:
    set_var(menu, bar)