简体   繁体   中英

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). Also avoid nested functions.

Instead make "m" a class attribute so it will be accessible throughout the class.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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