Search code examples
pythontkinteroptionmenu

Get a list of all options from OptionMenu


I want to get a list of all options from an OptionMenu widget in tkinter like so:

import tkinter

root = tkinter.Tk()

var = tkinter.StringVar(root)
var.set('OptionMenu')
optionMenu = tkinter.OptionMenu(root, var, 'foo1', 'foo2')
optionMenu.pack()

listOfAllOptions = optionMenu.getOptions()
# listOfAllOptions == ['foo1', 'foo2']

root.mainloop()

Is there a function that achieve that ? If not what is the workaround?


Solution

  • You can get the menu associated with the optionmenu (eg: optionMenu["menu"]), and with that you can use menu methods to get the items. It takes several lines of code. But honestly, the easiest thing to do is put the values in a list that you attach to the widget (eg: optionMenu.items = the_list_of_values)

    If you want to pull the data from the actual widget, you would do something like this:

    menu = optionMenu["menu"]
    last = menu.index("end")
    items = []
    for index in range(last+1):
        items.append(menu.entrycget(index, "label"))
    print "items:", items