简体   繁体   English

python tkinter:当它们成组时,如何获取单选按钮的IntVar()

[英]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 这样我可以在每个组中选择1个单选按钮,但是我不能使用get()方法来检查选择了哪个

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 我可以使用get()方法,但是我可以同时选择所有按钮,而这并不是我所需要的,每个组只能选择一个单选按钮

thank you for your help 谢谢您的帮助

You can't use a normal integer as the value for the variable option. 您不能使用普通整数作为variable选项的值。 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. 您必须提供tkinter变量之一作为variable选项的值。 All radiobuttons with the same variable will be tied together in a group. 具有相同variable所有单选按钮将捆绑在一起。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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