简体   繁体   English

在python pyqt5中单击后如何禁用按钮命令?

[英]How to disable the button command after clicking on it in python pyqt5?

Is there a way to disable the command after clicking on it.有没有办法在单击后禁用该命令。

I have tried to make it using the code below.我尝试使用下面的代码来实现它。

from PyQt5.QtWidgets import * 
import sys
class window(QWidget):
    def __init__(self):
        super().__init__()
        self.btn = QPushButton("click me")
        self.btn.clicked.connect(self.stopcommand_after_clicking)

        vbox  = QVBoxLayout()
        vbox.addWidget(self.btn)
        self.setLayout(vbox)
    def stopcommand_after_clicking(self):
        m = 1
        def clicked():
            global m#but after the command happens the value of m changes
                    # and so the command must not happen again
            m = 2
            print("clicked")
            pass
        if m == 1:#because m is equal to one the command is gonna happen
            
            clicked()
app = QApplication(sys.argv)
windo = window()
windo.show()
app.exec_()

apparently what happens that when I click the button again it goes through the value again and it changes the value later.显然,当我再次单击该按钮时,它会再次通过该值并稍后更改该值。

But it succeed when I make it with this method.但是当我用这种方法成功时它成功了。

m = 1
def do_it():
    global m
    m =0
while m == 1:
    do_it()
    print("m is equal to 1")

The problem is that "m" is a local variable that will be created and destroyed, and don't try to use global variables either, since they are unnecessary in addition to causing bugs that are often silent (which are the worst).问题在于“m”是一个将被创建和销毁的局部变量,并且也不要尝试使用全局变量,因为除了导致通常无声的错误(这是最糟糕的)之外,它们是不必要的。 Also avoid nested functions.还要避免嵌套函数。

Instead make "m" a class attribute so it will be accessible throughout the class.而是将“m”设为类属性,以便在整个类中都可以访问它。

class window(QWidget):
    def __init__(self):
        super().__init__()
        self.btn = QPushButton("click me")
        self.btn.clicked.connect(self.stopcommand_after_clicking)

        vbox = QVBoxLayout(self)
        vbox.addWidget(self.btn)

        self.m = 1

    def stopcommand_after_clicking(self):
        if self.m == 1:
            self.clicked()

    def clicked(self):
        self.m = 2
        print("clicked")

global m only refers to the use of the global variable m, it does not create a global variable, so in your case since there is no global variable then that line of code is useless. global m仅指使用全局变量 m,它不会创建全局变量,因此在您的情况下,由于没有全局变量,那么该行代码是无用的。 In your second code change "m" if it is a global variable so global m indicates that all the code after you use "m" (in its scope) will refer to the global object.在您的第二个代码中,如果“m”是全局变量,则更改“m”,因此global m表示使用“m”(在其范围内)后的所有代码都将引用全局对象。

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

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