PyQt5 QTimer 计数到特定秒数

PyQt5 QTimer count until specific seconds

我正在 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")

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

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