Search code examples
pythonpython-3.xtkinteroptionmenu

Get values from multiple tkinter option menus


I need to loop through option menus I have made in a for loop and store their values to a list when a button is pressed.

I have a for loop which makes a dynamic number of option menus (two columns, multiple rows). Here is my GUI for reference: imgur link

I store the option menu identity and string variable identity in lists: self.obox_Type_idx and self.obox_Role_idx

Here is my code:

for i in range(0,num_vars):
    self.lbl_VarName = Label(self.frm_widgets, text=X_columns[i], anchor='w')
    self.lbl_VarName.grid(row=i, column=0, sticky='news', padx=(0,20))

    typeopt = StringVar()
    obox_Type = OptionMenu(self.frm_widgets, typeopt, *self.obox_Type_input)
    obox_Type.config(width=15)
    obox_Type.grid(row=i, column=1, sticky='news', padx=(60,0))
    typeopt.set("numerical") #default value
    self.obox_Type_idx.append((obox_Type, typeopt))

    roleopt = StringVar()
    obox_Role = OptionMenu(self.frm_widgets, roleopt, *self.obox_Role_input)
    obox_Role.config(width=15)
    obox_Role.grid(row=i, column=2, sticky='news')
    roleopt.set("feature") #default value
    self.obox_Role_idx.append((obox_Role, roleopt))

Here's an example of an entry in self.obox_Type_idx: (<tkinter.OptionMenu object .!frame.!canvas.!frame.!optionmenu2>, <tkinter.StringVar object at 0x09835870>)

So my goal is to loop through the Type column and store all of the optionmenu selections to list when another button is pressed. And the same for the Role column in its own list. I can add a command to the optionmenu to get it to print the selected value, but I need to be able to loop through the distinct menus and get their specific value.


Solution

  • All you have to do is to loop through self.obox_Type_idx and use the get method of the StringVar to get the current selection of the optionmenu:

    def on_press(self):
         self.list_Role = [var.get() for menu, var in self.obox_Role_idx]
    

    and create a button whose command is on_press. When this button is pressed, then the list of selected roles is stored in self.list_Role.