Search code examples
pythontkinteroptionmenu

OptionsMenu display only first item in each list?


Here I have a basic OptionsMenu and a list with lists inside of it for my Menu options. What I need to do is display only the first item of the sub lists in the options menu but when that item is selected to pass the 2nd item in the sub list to a function.

Currently I can display all of the sub list and pass all of the sub list to a function. The main problem I am having is trying to display JUST the first item "ID 1" or "ID 2" in the drop down menu.

import tkinter as tk


root = tk.Tk()

def print_data(x):
    print(x[1])

example_list = [["ID 1", "Some data to pass later"], ["ID 2", "Some other data to pass later"]]
tkvar = tk.StringVar()
tkvar.set('Select ID')

sellection_menu = tk.OptionMenu(root, tkvar, *example_list, command=print_data)
sellection_menu.config(width=10, anchor='w')
sellection_menu.pack()

root.mainloop()

This is what I get:

enter image description here

What I want:

enter image description here

As you can see in the 2nd image only the "ID 1" is displayed in the menu and the data for that ID is printed to console.

I cannot find any documentation or post abut this issue so it may not be possible.


Solution

  • The only way I can think about is this

    import tkinter as tk
    
    
    root = tk.Tk()
    

    do a for loop that takes the first index and that is the ID

    sellection_menu = tk.OptionMenu(root, tkvar,
                                *[ID[0] for ID in example_list],
                                command=print_data)
    

    search for the given index but this is slow and not so good if you are using a lot of data

    def print_data(x):
        for l in example_list:
            if x == l[0]:
                print(l[1])
                break
    
    
    example_list = [["ID 1", "Some data to pass later"], 
                    ["ID 2", "Some other data to pass later"]]`