简体   繁体   中英

python tkinter: how i can get the IntVar() for radiobutton when they are in groups

I have the following problem, I need to check which radiobutton is active and get its value, for example...

radio1 = Radiobutton(mainframe,text='rbutton1', value=1, variable=1)
radio2 = Radiobutton(mainframe,text='rbutton2', value=2, variable=1)
radio3 = Radiobutton(mainframe,text='rbutton3', value=3, variable=2)
radio4 = Radiobutton(mainframe,text='rbutton4', value=4, variable=2)

with this i can select 1 radiobutton in each group but i can't use the get() method to check which one is selected

but when i use this example...

var = IntVar()
radio1 = Radiobutton(mainframe,text='rbutton1', value=1, variable=var)
radio2 = Radiobutton(mainframe,text='rbutton2', value=2, variable=var)
radio3 = Radiobutton(mainframe,text='rbutton3', value=3, variable=var)
radio4 = Radiobutton(mainframe,text='rbutton4', value=4, variable=var)

i can use the get() method but i can select all buttons at the same time and that is not what i need, every group can only have one selected radiobutton

thank you for your help

You can't use a normal integer as the value for the variable option. Well, you can, as your code illustrates, but there is no way to get the value back out.

You must provide one of the tkinter variables as the value of the variable option. All radiobuttons with the same variable will be tied together in a group. If you want two groups, you will need to use two variables. Also, you should initialize the varibles to have one of the allowed values, otherwise your radiobuttons will likely not be in the state that you expect.

group1 = IntVar(value=1)
group2 = IntVar(value=3)

radio1 = Radiobutton(mainframe,text='rbutton1', value=1, variable=group1)
radio2 = Radiobutton(mainframe,text='rbutton2', value=2, variable=group1)

radio3 = Radiobutton(mainframe,text='rbutton3', value=3, variable=group2)
radio4 = Radiobutton(mainframe,text='rbutton4', value=4, variable=group2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM