本文介绍了PyQt5 QTimer计数到特定的秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用python创建程序,并且正在使用pyqt.我目前正在使用QTimer,我想每秒钟打印一次"timer works",并在5秒钟后停止打印.这是我的代码:
I am creating a program in python and i am using pyqt. I am currently working with the QTimer and i want to print "timer works" every seconds and stop printing after 5 seconds. Here is my code:
timers = []
def thread_func():
print("Thread works")
timer = QtCore.QTimer()
timer.timeout.connect(timer_func)
timer.start(1000)
print(timer.remainingTime())
print(timer.isActive())
timers.append(timer)
def timer_func():
print("Timer works")
推荐答案
下面是一个简单的演示,展示了如何创建一个在固定的超时时间后停止计时的计时器.
Below is a simple demo showing how to create a timer that stops after a fixed number of timeouts.
from PyQt5 import QtCore
def start_timer(slot, count=1, interval=1000):
counter = 0
def handler():
nonlocal counter
counter += 1
slot(counter)
if counter >= count:
timer.stop()
timer.deleteLater()
timer = QtCore.QTimer()
timer.timeout.connect(handler)
timer.start(interval)
def timer_func(count):
print('Timer:', count)
if count >= 5:
QtCore.QCoreApplication.quit()
app = QtCore.QCoreApplication([])
start_timer(timer_func, 5)
app.exec_()
这篇关于PyQt5 QTimer计数到特定的秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!