绑定变量到PyQt单选按钮
我正在使用PyQt4,想要设置一组单选按钮,根据选择来改变一个变量的值。显然,我可以用很多个IF语句来实现(比如10个单选按钮),但我觉得应该有更优雅的方法来做到这一点。
为了更清楚,我用伪代码来说明:
radiobutton1 = 52
radiobutton2 = 31
radiobutton3 = 773
if radiobutton1 x = 52
if radiobutton2 x = 31
if radiobutton3 x = 773
1 个回答
1
试试这个或者类似的方法,逐个遍历你的控件集合:
for i in range(1,4):
widgetname = 'radiobutton' + str(i)
if widgetname.isChecked():
return widgetname.value
你也可以把单选按钮放在一个列表里,然后通过这个对象列表来遍历,而不是用字符串操作。举个例子:
rb_list = [ rb1, rb2, rb3 ] # where items are your radio buttons
#these can be appended to the list when the objects are created
def rb_check(rbl=rb_list):
for rb in rbl:
if rb.isChecked():
print("RadioButton", rb, "is checked.") # or return value
希望这能帮到你。