python - 在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”,如果它是一个全局变量,那么global m
表明您使用“m”(在其范围内)之后的所有代码都将引用全局对象。
推荐阅读
- php - laravel elasticsearch搜索和分页结果
- php - 在 Dockerfile 中“php artisan storage:link”返回一个非零代码
- c++ - 如果未在 .txt 文件中声明,则使用 ifstream 分配默认值
- angular - 如何使用@Inject 并获取不在构造函数中的服务实例?
- php - 仅显示 MySQL 列值计数
- vue.js - JEST @vue/composition-api + Jest 测试套件无法运行 [vue-composition-api] 在使用任何函数之前必须调用 Vue.use(VueCompositionAPI)
- c - 库插入
- javascript - 获取 URL 路径字符串 JS 中的值
- javascript - 使用 JSON 使用 JavaScript 和 HTML 构建表格
- c++ - 设置移动 box2d 对象的线速度(自身速度 + 玩家速度)