在 Python PySide2 中使用 sleep 时如何查看同一函数的多个变化
How to see more than one change in same function when using sleep in Python PySide2
我试图在同一个函数中执行多个操作。在下面的代码中,您将看到一个带有按钮和标签的 window 页面。我想看到 "BLUE",睡了 2 秒后,我想在我的标签上看到 "RED" 文本。但是当我单击按钮时,所有功能都像一个块一样工作,并且在 slepp 两秒后标签文本变为 "RED"。是的,首先它变为蓝色,但我看不到,因为它太快了。我该如何解决?
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
#label is Hello now
self.label=QLabel("Hello")
self.button = QPushButton("Change it")
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
self.button.clicked.connect(self.func)
def func(self):
self.label.setText("BLUE")
time.sleep(2)
self.label.setText("RED")
void QTimer::singleShot(int msec, const QObject *receiver, const char *member)
This static function calls a slot after a given time interval.
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
#label is Hello now
self.label = QLabel("Hello")
self.button = QPushButton("Change it")
self.button.clicked.connect(self.func)
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
def func(self):
self.label.setText("BLUE")
# QApplication.processEvents()
# QThread.msleep(2000)
# self.label.setText("RED")
QTimer.singleShot(2000, lambda : self.label.setText("RED")) # <----
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = Form()
w.show()
sys.exit(app.exec_())
我试图在同一个函数中执行多个操作。在下面的代码中,您将看到一个带有按钮和标签的 window 页面。我想看到 "BLUE",睡了 2 秒后,我想在我的标签上看到 "RED" 文本。但是当我单击按钮时,所有功能都像一个块一样工作,并且在 slepp 两秒后标签文本变为 "RED"。是的,首先它变为蓝色,但我看不到,因为它太快了。我该如何解决?
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
#label is Hello now
self.label=QLabel("Hello")
self.button = QPushButton("Change it")
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
self.button.clicked.connect(self.func)
def func(self):
self.label.setText("BLUE")
time.sleep(2)
self.label.setText("RED")
void QTimer::singleShot(int msec, const QObject *receiver, const char *member)
This static function calls a slot after a given time interval.
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
#label is Hello now
self.label = QLabel("Hello")
self.button = QPushButton("Change it")
self.button.clicked.connect(self.func)
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button)
self.setLayout(layout)
def func(self):
self.label.setText("BLUE")
# QApplication.processEvents()
# QThread.msleep(2000)
# self.label.setText("RED")
QTimer.singleShot(2000, lambda : self.label.setText("RED")) # <----
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = Form()
w.show()
sys.exit(app.exec_())