Search code examples
pythontkinteroptionmenu

Virtual Events for tkinter Optionmenu


I've been looking around for quite a while now and I can't find what I'm looking for, so please let me know if this doesn't exist or isn't the best way of doing it.

I want to be able to trigger and event when an option is selected from an Optionmenu()

I also want it to use virtual events, similar to this: my_tree.bind('<<TreeviewSelect>>', function)

Is there a list that I can find all the virtual events for tkinter widgets?


Solution

  • I want to be able to trigger and event when an option is selected from an Optionmenu()

    The way to do that is to add a trace to the variable associated with the OptionMenu.

    colors = ("red", "orange", "yellow", "green", "blue", "indigo", "violet")
    color_var = tk.StringVar(value=colors[0])
    om = tk.OptionMenu(root, color_var, *colors)
    
    
    def color_callback(varname, idx, mode):
        print(f"the color changed to {root.getvar(varname)}")
    color_var.trace_add(("write", "unset"), color_callback)
    

    I also want it to use virtual events, similar to this: my_tree.bind('<>', function)

    The OptionMenu doesn't support virtual events, but you can create one if you want. In the callback for the trace you can generate a virtual event, which you can then bind to:

    def create_virtual_event(varname, idx, mode):
        om.event_generate("<<OptionMenuChanged>>")
    color_var.trace_add(("write", "unset"), create_virtual_event)
    
    def color_callback(event):
        print(f"the color changed to {color_var.get()}")
    om.bind("<<OptionMenuChanged>>", color_callback)
    

    Is there a list that I can find all the virtual events for tkinter widgets?

    The canonical list of all predefined virtual events is on the tcl/tk events man page.