How to update the command of an OptionMenu

后端 未结 3 1793
无人共我
无人共我 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:25

    Good question! Its a good thing I never had to do this in any one of my projects before because (unless someone proves me wrong here) you can't set/update the command of a OptionMenu widget once its already defined.

    If Tkinter wanted you to be able to do that, it definitely would've included it to be edited by .configure()

    There is a handy function called .keys() which you can call with a widget object to see all available traits that can be used with .configure().

    Button example:

    from tkinter import *
    
    master = Tk()
    
    def callback():
        print ("click!")
    
    b = Button(master, text="OK", command=callback)
    print (b.keys()) #Printing .keys()
    b.pack()
    
    mainloop()
    

    Which results in :

    Notice how in this huge list of keys, 'command' is on the second line? That is because a button's command CAN be used in .configure()

    OptionMenu example:

    from tkinter import *
    
    root = Tk()
    var = StringVar()
    
    def foo(val):
        print ("HI")
    
    widget = OptionMenu(root, var, "one", 'two')
    print(widget.keys())
    widget.pack()
    root.mainloop()
    

    Which results in:

    Notice how there is no 'command' on line 2 this time. This is because you cant configure command with an OptionMenu widget.

    Hopefully this problem doesn't hinder your program too much and I hope my answer helped you understand better!

提交回复
热议问题