How to update the command of an OptionMenu

后端 未结 3 1766
无人共我
无人共我 2021-01-23 01:56

I am trying to set or update the command of an OptionMenu after its instantiation.

The widget.configure(command=foo) statement works for Button

3条回答
  •  爱一瞬间的悲伤
    2021-01-23 02:24

    It is possible to change the commands associated with OptionMenu widets if you're careful (as @Bryan Oakley commented). Below is an example of doing it.

    The tricky part is you have to reconfigure all the menu items, not just one of them. This requires some extra bookkeeping (and some processing overhead, but it's unnoticeable).

    Initially the menu has three items, each with a different function to be called when selected, one of which changes the menu. If the latter is selected the menu is changed to only have two menu items both of which call the same function.

    from tkinter import *
    
    root = Tk()
    var = StringVar()
    var.set('Select')
    
    def foo(value):
        var.set(value)
        print("foo1" + value)
    
    def foo2(value):
        var.set(value)
        print("foo2 " + value)
    
    def foo3(value):
        var.set(value)
        print("foo3 " + value)
    
    def change_menu(value):
        var.set('Select')
        print('changing optionmenu commands')
        populate_menu(optionmenu, one=foo3, two=foo3)
    
    def populate_menu(optionmenu, **cmds):
        menu = optionmenu['menu']
        menu.delete(0, "end")
        for name, func in cmds.items():
            menu.add_command(label=name, command=
                             lambda name=name, func=func: func(name))
    
    optionmenu = OptionMenu(root, var, ())  # no choices supplied here
    optionmenu.pack()
    Label(root, textvariable=var).pack()
    
    populate_menu(optionmenu, one=foo, two=foo2, change=change_menu)
    
    root.mainloop()
    

提交回复
热议问题