如何在QRadioButton上多次点击但只运行一次功能?

时间:2016-06-17 12:18:40

标签: python qt-designer qpushbutton qradiobutton

我有2个单选按钮。第一个radio1连接到函数func(),在此函数内部将按钮pushButton连接到另一个函数print_me()

这是剥离的代码:

radio = self.dockwidget.radioButton
radio.clicked.connect(func)

def func():
    # Connect pushButton to "print_me" function
    connect = self.dockwidget.pushButton
    connect.clicked.connect(print_me)

def print_me():
    print 'Connected'

当用户点击radio1然后点击pushButton时,会打印一条消息。问题是,如果用户点击radio 10次,然后点击pushButton,则该消息也会打印10次。或者,如果用户点击radio1,然后点击radio2,然后返回radio1,它仍然会打印两次消息。

有没有办法防止这种情况,只有在单击任一按钮时,它才会打印一次消息?

1 个答案:

答案 0 :(得分:1)

拥有全局变量并将其设置为TrueFalse。然后在代码中添加if语句(在此示例中,全局变量名称为clicked_radio_button):

radio = self.dockwidget.radioButton
radio.clicked.connect(func)
clicked_radio_button = False #Set global variable
def func():
    if clicked_radio_button == False:
         # Connect pushButton to "print_me" function
         connect = self.dockwidget.pushButton
         connect.clicked.connect(print_me)
         clicked_radio_button = True #Set global variable to True
    else:
        pass #Do nothing if already pressed

def print_me():
    print 'Connected'