Home > OS >  Use loop to create x number of tkinter OptionMenu
Use loop to create x number of tkinter OptionMenu

Time:12-23

I am attempting to create an arbitrary number of optionmenus, but have trouble when trying to pull the StringVar() selected by each optionmenu.

Goal: Create an arbitrary number of optionmenus with consecutive names (up to that arbitrary number) and consecutive variable names keeping track of the current optiomenu value

For example if an optionmenu is as follows:

import tkinter as tk
from tkinter import *

root = tk.Tk()
root.geometry()

dropdown1 = StringVar()

Dropdownoptions = [
    "option1",
    "option2",
    "option3"
]

dropdownfirst = tk.OptionMenu(root, dropdown1, *Dropdownoptions)
dropdownfirst.grid(column=0, row=0)

root.mainloop()

If using a dictionary I do not know how to pull the values out of each Optionmenu. When looking at other questions about the use of dictionaries to create variables, most answers boil down to "Learn How to Use Dictionaries" instead of answering the questions.

There was a very similar problem posted in Tkinter Create OptionMenus With Loop but sadly it is not applicable in my case.

New code with grid and non-working button:

import tkinter as tk


def erase_option():
    for (name, var) in options.items():
        print(var.get())
        # print(options['optionmenu4'])
        name.grid_forget()


root = tk.Tk()

Dropdownoptions = [
    "option1",
    "option2",
    "option3"
]

maxval = 10

options = {}
for om, x in zip(range(maxval), range(maxval)):
    name = f"optionmenu{om}"
    var = tk.StringVar()
    options[name] = var
    name = tk.OptionMenu(root, var, *Dropdownoptions)
    name.grid(column=0, row=x)

button = tk.Button(root, text="Erase 5th option", command=erase_option)
button.grid(column=0, row=maxval)

root.mainloop()

CodePudding user response:

Give each optionmenu its own StringVar instance. Save those instances in a list or dictionary. To get the values, iterate over the list.

The following code creates a dictionary named options. It creates a series of variables and optionmenus in a loop, adding each variable to this options dictionary. The function print_options iterates over the list printing out the key and value for each option.

import tkinter as tk

def print_options():
    for (name, var) in options.items():
        print(f"{name}: {var.get()}")

root = tk.Tk()

Dropdownoptions = [
    "option1",
    "option2",
    "option3"
]
options = {}
for om in range(10):
    name = f"Option {om}"
    var = tk.StringVar(value="")
    options[name] = var
    om = tk.OptionMenu(root, var, *Dropdownoptions)
    om.pack()

button = tk.Button(root, text="Print Options", command=print_options)
button.pack(side="bottom")

root.mainloop()
  • Related