简体   繁体   中英

Tkinter get OptionMenu Option List

I'm using Python 3, Tkinter module. I've looked at ttk library and one of the widgets there is an Option Menu. It's great, but I was wondering if there is a way to retrieve the list of options that are currently in use by the menu.

In this example:

Options_List=["option1","option2"]
My_Menu = OptionMenu(master, variable, *Options_List))

I'm aware that it may seem trivial. Just retrieve the Options_List variable. But now let's assume I'm making loads of options (using the same, or different lists):

Options_List=["option1","option2","option3"]
Menu_List = []
for Option in range(3):
    My_Menu = OptionMenu(master, variable, *Options_List))
    Menu_List.append(My_Menu)
    Options_List.del(-1) #removes last item

I just took advantage of the fact that when the Option Menu is assigned, the options are the copy of the Options_List variable, not a reference to it, so when the code is executed, they all refer to their own version of Options_List .

Option output would yield:

Menu_List[0] -> ["option1","option2","option3"]
Menu_List[1] -> ["option1","option2"]
Menu_List[2] -> ["option1"]

Now you can see that I can't just retrieve Options_List , because each Option Menu has its own list to work off.

So, any ideas? Is there any way I can get hold of the list of options that my nth Option Menu is using?

The option menu is nothing more than a standard button with a menu attached to it. So, to get the values in the option menu you simply need to get the menu associated with the optionmenu, and use the methods available on the menu to get the items on the menu.

For example, let's assume that om represents the optionmenu. To get the menu you can do this:

menu = om['menu']

menu now is a reference to a Menu object. You can find out the index of the last item with the index method:

    last_index = menu.index("end")

With that, you can iterate over the items in the menu. If you want the label, you can use entrycget to get the value of that attribute:

    values = []
    for i in range(last_index+1):
        values.append(menu.entrycget(i, "label"))

With that, values will contain the values that appear on the menu.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM