Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 284
TheLastOfTheMoops Avatar asked Oct 22 '25 06:10

TheLastOfTheMoops


1 Answers

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
like image 135
Bryan Oakley Avatar answered Oct 23 '25 20:10

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!