[英]How to make button to perform multiple actions properly in PyQT5
Below is my test code.下面是我的测试代码。 I'm trying to update the text of my label 2 times with a 10-sec delay in between when clicking the Button .
我正在尝试更新我的 label 的文本 2 次,在单击Button时有 10 秒的延迟。 However, it seems to always ignore the first action , in this case, which is
self.display.setText("First")
and run the second.但是,它似乎总是忽略第一个动作,在这种情况下,即
self.display.setText("First")
并运行第二个。 I purposely put a 10-sec delay in between the actions to make sure the label not changing so fast that I can't see.我特意在两个动作之间延迟了 10 秒,以确保 label 的变化不会太快以至于我看不到。 I also tried swapping places of the first and second actions.
我还尝试交换第一个和第二个动作的位置。 Again, whichever is supposed to happen first is completely ignored.
同样,无论哪个应该先发生,都会被完全忽略。 Please help!
请帮忙!
import PyQt5.QtWidgets as qtwidget
import time
app = qtwidget.QApplication([])
class MainWindow(qtwidget.QWidget):
def __init__(self):
super().__init__()
# Set window title
self.setWindowTitle('Python')
height = 100
width = 500
self.status = "stop"
# Set fixed window size
self.setFixedHeight(height)
self.setFixedWidth(width)
self.display = qtwidget.QLabel("Label")
self.display.setStyleSheet("background-color: #e3e1da;\
border: 1px solid black;\
padding-left: 5px")
self.btn1 = qtwidget.QPushButton("Button", self)
self.btn1.clicked.connect(self.button_action)
# Set progam main layout
main_layout = qtwidget.QVBoxLayout()
# Create horizontal box for buttons
sub_layout = qtwidget.QHBoxLayout()
# Add buttons to horizontal box
sub_layout.addWidget(self.btn1)
# Add horizontal layout to vertical box layout
main_layout.addLayout(sub_layout)
main_layout.addWidget(self.display)
self.setLayout(main_layout)
self.show()
def button_action(self):
self.display.setText("First")
time.sleep(5)
self.display.setText("Second")
mw = MainWindow()
app.exec_()
Taking feedback from the comments.从评论中获取反馈。 I've modified my code and it's now working as intended.
我已经修改了我的代码,它现在按预期工作。
def button_action(self):
self.display.setText("First")
qtcore.QTimer.singleShot(100, lambda: self.test_function())
def test_function(self):
self.display.setText("Second")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.