Creating several tkinter widgets in a for loop and assigning them to variables

Viewed 1055

In a recipe book about Python/tkinter, I found this snippet on how to create three Radiobutton widgets within one loop:

colors = ["Blue", "Gold", "Red"]
radVar = tk.IntVar()
radVar.set(99)                   

for col in range(3):                          
    curRad = 'rad' + str(col)
    curRad = tk.Radiobutton(win, text=colors[col],         variable=radVar,
         value=col,
         command=radCall)

    curRad.grid(column=col, row=5, sticky=tk.W)

I get the point of using a loop, but I would expect the variable curRad to be used for instance as a list, ending up containing references to all those Radiobuttons. What is hapening here? Is Python somehow creating custom-named variables at each iteration? To me it looks like we're assigning a string to a variable and then assigning a reference to a widget to the same variable, and doing the same at each iteration.

What am I missing here?

2 Answers

I really like your solution, jason. You can reference later the buttons through the indexes of the list generated.

You can also create the buttons as follow

for col in range(3):                          
    globals()["curRad" + str(col)] = tk.Radiobutton(win, text=colors[col], variable=radVar, value=col, command=radCall)

So the name of the variables associated to each button will be different, in this case:

curRad0

curRad1

curRad2

Related