0

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?

SlavaCat
  • 101
  • 6
  • Does this answer your question? [How to detect when an OptionMenu or Checkbutton change?](https://stackoverflow.com/questions/5308142/how-to-detect-when-an-optionmenu-or-checkbutton-change) – Thingamabobs Apr 18 '21 at 16:50
  • No, I want to use virtual events, not .trace() – SlavaCat Apr 18 '21 at 16:52

1 Answers1

1

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685