Tkinter radio buttons created in a for loop change to the same value when any one of them is pressed


I’m creating a linear regression tool with a simple UI using Tkinter, and today I’ve been trying to create a frame in which there will be several things: the 0th column will contain labels with variable names that I’ve extracted from an Excel/CSV dataset, and next to every label there will be three radio buttons, each altering the values of their respective variable to values of 1, 0, or 2. Everything looks good in the frame, except one critical fact – say I have variables var1, var2, var3, and I want to change the value of var1 to 2. When I click and change var 1 to the value 2, var2 and var3 change to this value as well.

def variablenameframe():
    global column_names #list containing variable names
    global variabletype #list which will contain radiobutton values for every variable
    Label(variablenameframe,text="Don't use").grid(row=0,column=2)
    for j in range(len(column_names)):
        Radiobutton(variablenameframe,variable=variabletype[j], value=1).grid(row=i,column=1)
        Radiobutton(variablenameframe,variable=variabletype[j], value=0).grid(row=i,column=2)
        Radiobutton(variablenameframe,variable=variabletype[j], value=2).grid(row=i,column=3)

Result of the code:

I’m assuming the problem is something about creating the buttons through a for loop that I don’t yet understand? I’m still very new to Python and Tkinter so I have no idea where to go from here, so any feedback would be much appreciated.

Asked By: cocobolodesk



Most of this looks fine. Your crucial mistake is not creating a fitting variable per row. In case of a radio button, use tk.IntVar(). Additionally, to make your code a bit cleaner, I would get rid of either the ‘i’ or ‘j’ variable. Your code then becomes:

def variablenameframe():
    for i in range(len(column_names)):
        Radiobutton(variablenameframe,variable=variabletype[i], value=1).grid(row=i+1,column=1)
        Radiobutton(variablenameframe,variable=variabletype[i], value=0).grid(row=i+1,column=2)
        Radiobutton(variablenameframe,variable=variabletype[i], value=2).grid(row=i+1,column=3)
Answered By: RCTW
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.