4

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?

1 Answers1

8

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
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thanks for the comments. about the solution - I am looking just for that way so i won't have to save the changes i made in a different way. so I'd appreciate if you share with me the solution how to get the options from the widget itself – TheLastOfTheMoops Mar 09 '16 at 15:05