PYQT5张标签使用循环文本
代码从错误中很干净,但是运行程序何时会冻结 该程序使用按钮的倒计时开始倒计时 下面的图片设置了布局 在此处输入图像说明
probelm正在使用循环来更改标签文本,并使程序变得冻结
from time import sleep
import PyQt5.QtWidgets as Qtw
class MainWindow(Qtw.QWidget):
def __init__(self):
super().__init__()
self.setLayout(Qtw.QVBoxLayout())
pushButton = Qtw.QPushButton("start",clicked = lambda: setting_label())
self.layout().addWidget(pushButton)
my_label = Qtw.QLabel("00:00:00")
self.layout().addWidget(my_label)
self.show()
def setting_label():
t = 1200
while t:
h = t // 3600
m = t // 60
s = t % 60
timer = "{:02d}:{:02d}:{:02d}".format(h,m,s)
my_label.setText(timer)
sleep(1)
t -= 1
app = Qtw.QApplication([])
window = MainWindow()
app.exec_()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代码写在OP中的方式,它并没有真正被卡住或冻结。但是,显示显示未能更新。您可以通过尝试强迫QT使用
app.processevents()
来更新GUI来解决此问题。将其放入setter_label
函数之后:使用
app.processevents()
的首选方式通常会灰心。制作倒数计时器的另一种方法是使用a qtimer 。设置所有信号和插槽时,还有更多的开销。但这可能非常强大。这是一个例子
The way the code is written in the OP, it doesn't really get stuck or frozen. But rather, the display fails to update. You can get around this by trying to force Qt to update the GUI with
app.processEvents()
. Put it in yoursetting_label
function after the setText():The Preferred Way
Using
app.processEvents()
a lot is usually discouraged. Another way to make a countdown timer is to use a QTimer. There is a little more overhead in setting up all of the signals and slots. But it can be very powerful. Here is an example编辑:此解决方案适用于OP,但其他人指出,使用
螺纹
进行此操作可能会导致意外行为,崩溃等。因此,最好使用其他方法进行此操作(例如:此答案接收输入)。您可以通过将函数移动到这样的线程来解决此问题:
Edit: This solution works for the OP, but others have pointed out that doing this using
threading
can cause unexpected behavior, crashes, etc. so it's better to do this using other methods (for example: this answer)The interface freezes because the while loop you use to change the label blocks the event loop of the app (i.e. receiving inputs). You can fix this by moving the function to a thread like this: