0

I would like to generically create ComboBox from a list of objects (infos). I created the program below. My problem is to show the default value of the Combobox. I use a Stringvar for this. But the default value is only displayed in the last created Combobox. I think is because my StringVar is unique for all ComboBox but I don't know how to fix the problem. How can I do this?

counter = 0

for i in infos:
        frame = Frame(principalFrame, bd=1)
        frame.grid(row=counter, column=0, pady=20)
        frame.columnconfigure(0,weight=1)

        label = Label(frame, text=i.name)
        label.grid(row=0, column=0, sticky="news")
        label.columnconfigure(0,weight=1)

        varCombo = StringVar(window)
        varCombo.set(i.default)

        combo = ttk.Combobox(frame, state="readonly", textvariable=varCombo, values=i.values)
        combo.grid(row=1, column=0, sticky="news")
        combo.columnconfigure(0, weight=1)
        combo.rowconfigure(0, weight=1)

        counter = counter + 1
poolpy
  • 31
  • 5

2 Answers2

1

Since you use same variable varCombo for the StringVar, only the last instance of the StringVar has reference to it, the others will be garbage collected.

If you want to access those StringVar later, better use a dictionary to store them:

varCombo = {}
counter = 0
for i in infos:
    frame = Frame(principalFrame, bd=1)
    frame.grid(row=counter, column=0, pady=20)
    frame.columnconfigure(0,weight=1)

    label = Label(frame, text=i.name)
    label.grid(row=0, column=0, sticky="news")
    label.columnconfigure(0,weight=1)

    var1 = StringVar(window)
    var1.set(i.default)

    combo = ttk.Combobox(frame, state="readonly", textvariable=var1, values=i.values)
    combo.grid(row=1, column=0, sticky="news")
    combo.columnconfigure(0, weight=1)
    combo.rowconfigure(0, weight=1)
    varCombo[i.name] = var1

    counter = counter + 1
acw1668
  • 40,144
  • 5
  • 22
  • 34
0

combo = ttk.Combobox(frame, state="readonly", textvariable=varCombo, values=i.values)

Every time the loop runs a new combobox is assigned to the variable combo, but the final value of the combo box is being set in the last iteration so, only the last value is being reflected. You can use a class to tackle this. Please check the below link:

Set a default value for a ttk Combobox