Austin
Austin

Reputation: 103

How to select one Tkinter Radiobutton per variable

I am trying to make a loop that populates 9 radio buttons, each with 4 options, and placed in a grid. The following code words, however, I can select more than one option for each question. My understanding is that for each variable I should only be able to select one. Is the loop constructed incorrectly?


MODES = [
    ('dep_name1', 'dep_but1', 2, "Not at all", 'op1'),
    ('dep_name2', 'dep_but2', 3, "Several days", 'op2'),
    ('dep_name3', 'dep_but3', 4, "More than half the days", 'op3'),
    ('dep_name4', 'dep_but4', 5, "Nearly everyday", 'op4'),
    ]

for r in range (2, 11):
    for dep_name, button, c, text, b_val in MODES:
        button = tk.StringVar()
        # button.set("L")
        dep_name = tk.Radiobutton(window, text=text, variable=button, indicatoron=0, value=b_val).grid(row=r, column=c, sticky='e')

window.columnconfigure("all", weight=1)
window.rowconfigure("all", weight=1)


window.mainloop()

Upvotes: 2

Views: 165

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386362

You are creating one variable for each radiobutton. You should have one variable for each group of radiobuttons.

Since the variable can have only one value at a time, tkinter uses the variable to know which radiobuttons belong to a logical group. That is to say, all radiobuttons with the same variable are one logical group of buttons.

Here's one way to do it:

vars = []
for r in range (2, 11):
    var = tk.StringVar(value="op1")
    vars.append(var)
    for dep_name, button, c, text, b_val in MODES:
        tk.Radiobutton(window, text=text, variable=var, indicatoron=0, value=b_val).grid(row=r, column=c, sticky='e')

This example saves the variables to a list so that you can reference them by index elsewhere in your code.

I don't quite understand what dep_name and dep_button are supposed to represent. In both cases you initialize them from MODES, but then you change them inside the loops. Regardless, the point is that you need to create the variable just inside the outer loop so that you create one variable for each group of radiobuttons.

Upvotes: 1

Related Questions