简体   繁体   English

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

[英]How to click multiple times on QRadioButton but only run function once?

I have 2 radio buttons. 我有2个单选按钮。 The first one, radio1 , is connected to a function func() and inside this function connects a push button, pushButton , to another function print_me() . 第一个radio1连接到函数func()并且在此函数内部将按钮pushButton连接到另一个函数print_me()

This is the code stripped down: 这是简化的代码:

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'

When the user clicks radio1 and then pushButton , a message is printed. 当用户单击radio1然后单击radio1 ,将pushButton一条消息。 Problem is if the user clicks radio 10 times and then pushButton , the message is also printed 10 times. 问题是,如果用户单击radio pushButton 10次​​,然后pushButton ,则消息也会被打印10次。 Or if the user clicks radio1 , then radio2 , and back to radio1 , it will still print the message twice. 或者,如果用户单击radio1 ,然后单击radio2 ,并返回radio1 ,它将仍然打印两次消息。

Is there a way to prevent this so that it will only print the message once when either radio button is clicked? 有没有一种方法可以防止这种情况,以便在单击任一单选按钮时仅将消息打印一次?

Have a global variable and set it to either True or False . 有一个全局变量并将其设置为TrueFalse Then add an if statement to your code (In this example the global variable name is clicked_radio_button ): 然后在代码中添加一个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'

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

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