Having an issue with using combobox.set

I’m new to python, but have written code in various languages in the past (30+years ago). My issue is that I have five comboboxes defined and they work as expected, but in setting them up I want to use combobox.set to show the choice made the last time the program ran. This was saved to a file and the program reads it just fine. the problem is that the text for the last combobox created is displayed on all five of the boxes. I have tested this using just a string and the same thing happens. This is the test code for two of the boxes.

##Sheets
sheet_combobox=ttk.Combobox(root,width=14,height=6,textvariable=txt)
input_file=open(sheets_data_file,'r')
items=['']
for item in input_file:
    items.append(item)
sheet_combobox['values']=items
sheet_combobox.set("Select Sheet")
sheet_combobox.grid(column=0,row=3)

##Types
type_combobox=ttk.Combobox(root,width=14,height=6,textvariable=txt)
input_file=open(types_data_file,'r')
items=['']
for item in input_file:
    items.append(item)
type_combobox['values']=items
#type_combobox.set("Select Type")
type_combobox.grid(column=1,row=3)

Select Type appears in all boxes.

A posted example should be minimal (nothing extra not needed to illustrate the problem) and complete (can be run by others by copying and pasting. The latter means to include minimal data in the code itself.

With 3.12.0a1 on Windows I ran the following from an IDLE editor

import tkinter as tk
from tkinter import ttk

r = tk.Tk()
c1 = ttk.Combobox(r, values=('a','b'))
c1.set('a')
c1.pack()
c2 = ttk.Combobox(r, values=('a','b'))
c2.set('b')
c2.pack()
r.mainloop()

and c1 and c2 are set to ‘a’ and ‘b’ respectively.

One of the virtues of stripping your code down to the minimum, or of starting with the minimum and testing after each addition, is that you may see exactly what causes a problem. If you were to cut your code down a step at a time, (or build from my code) you would discover your problem disappears when you remove one of the textvariable options (or appear when you added the second text variable option). Do you see why?

1 Like

My guess is that you’re using (i.e. sharing) the same tkinter variable for both comboboxes (textvariable=txt), so setting one combobox changes the tkinter variable, which, in turn, changes the other combobox.

Thank you, Matthew, that is indeed the problem. In my newness, I didn’t see that my attempt to make dealing with a change in the boxes more efficient, caused the problem.

The duplication of textvariable is what I pointed at, while trying to show you how you could have discovered the problem.