繁体   English   中英

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

[英]How to disable the button command after clicking on it in 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")

问题在于“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”是全局变量,则更改“m”,因此global m表示使用“m”(在其范围内)后的所有代码都将引用全局对象。

暂无
暂无

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

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