Search code examples
pythonuser-interfacetkintercallbackoptionmenu

Access OptionMenu items - Tkinter


I have four OptionMenu, each OptionMenu has been populated with the a list of entries (the same for every menu).

from tkinter import *

def selected (event):
    print (clicked.get())

window = Tk()

entries = ["a", "b", "c", "d"]

for i in range (4):
    window.rowconfigure (i, minsize = 5)
    a_frame = Frame (master = window)
    a_frame.grid (row = i, column = 0, padx = 1, pady = 1)
    clicked = StringVar()
    clicked.set (entries[0])
    a_menu = OptionMenu (a_frame, clicked, *entries, command = selected)
    a_menu.pack()

window.mainloop()

I'm trying to access the value selected from each OptionMenu, but I'm getting printed only the values from the bottom OptionMenu. When I select some values from the other drop down menus, the action is "detected" but only the value from the bottom OptionMenu is being printed. If you try and run the code above, you can easily understand what I mean. How can I access each value I select from each OptionMenu? Many thanks in advance!


Solution

  • OptionMenu constructor:

    OptionMenu(parent, variable, choice1, choice2, ...)

    from tkinter import Tk, StringVar, OptionMenu
    
    def callback(arg):
        print(arg)
    
    root = Tk()
    option = StringVar()
    op = OptionMenu(root, option, 'a', 'b', 'c', 'd', command=callback)
    op.grid()
    option.set('a')
    root.mainloop()
    

    This is the basic which you can start with. When calling callback function it passes your choice as argument and print only the argument to console.

    Hope you have now a basic understanding.

    So in your case you need to print the argument not "print (clicked.get())"

    Try this one:

    from tkinter import *
    
    def selected (event):
        print (event)
    
    window = Tk()
    
    entries = ["a", "b", "c", "d"]
    
    for i in range (4):
        window.rowconfigure (i, minsize = 5)
        a_frame = Frame (master = window)
        a_frame.grid (row = i, column = 0, padx = 1, pady = 1)
        clicked = StringVar()
        clicked.set (entries[0])
        a_menu = OptionMenu (a_frame, clicked, *entries, command = selected)
        a_menu.pack()
    
    window.mainloop()