首页 > 解决方案 > 在python pyqt5中单击按钮命令后如何禁用它?

问题描述

有没有办法在点击命令后禁用它。

我试图使用下面的代码来实现它。

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_()

显然会发生什么,当我再次单击该按钮时,它会再次遍历该值并稍后更改该值。

但是当我用这种方法制作它时它成功了。

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

标签: pythonpyqt5

解决方案


问题是“m”是一个将被创建和销毁的局部变量,也不要尝试使用全局变量,因为它们是不必要的,而且会导致通常无声的错误(这是最糟糕的)。还要避免嵌套函数。

而是将“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仅指使用全局变量m,它不会创建全局变量,因此在您的情况下,由于没有全局变量,那么该行代码是无用的。在您的第二个代码中更改“m”,如果它是一个全局变量,那么global m表明您使用“m”(在其范围内)之后的所有代码都将引用全局对象。


推荐阅读