I'm trying to set the value in an OptionMenu by the index of the options, and not use the actual option value itself.
For example, if my OptionMenu has options ["one", "two", "three"], I want to be able to set it to "one" by writing My_Option_Menu.set(options[0])
, not My_Option_Menu.set("one")
The OptionMenu is dynamically populated by a list depending on what two other OptionMenus are set to, which is why I want to refer to the options by index and not actual value. Does the OptionMenu object have a way to return the list of options that are currently populated so that my options[0]
method above will work?
The simplest way to do this is to keep a copy of the list used to define the optionmenu. Then you can use the index to get the value from the list and assign it to the associated variable.
For example:
options = ["one","two","three"]
...
self.menuVar = tk.StringVar(master)
self.optionMenu = tk.OptionMenu(master, self.menuVar, *options)
...
self.menuVar.set(options[0])
Another option is to get the menu object associate with the widget, and use menu commands to get the text at the given index, and use that to set the variable:
value = self.optionMenu["menu"].entrycget(0, "label")
self.menuVar.set(value)