PyQt5 QTimer计数直到特定秒

2024-06-13 07:15:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python创建一个程序,并使用pyqt。我目前正在使用QTimer,我想每秒钟打印一次“timer works”,5秒钟后停止打印。这是我的代码:

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")

Tags: 代码程序deftimeoutthreadpyqtfuncprint
1条回答
网友
1楼 · 发布于 2024-06-13 07:15:13

下面是一个简单的演示,演示如何创建一个计时器,该计时器在固定的超时次数后停止。

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_()

相关问题 更多 >