2017-10-09 169 views
1

我正在python中创建一个程序,我正在使用pyqt。我目前正在使用QTimer,我想每秒打印一次“定时器工作”并在5秒后停止打印。这里是我的代码:PyQt5 QTimer计数,直到特定的秒

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

'QTimer'类不支持在固定数量的超时后停止。你必须保持计数并明确地停止它。 – ekhumoro

+0

你能为我做一个演示吗?我只是一个初学者。 – Jaypee

回答

0

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

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

哇!这是我一直在寻找'。在这里感谢朋友! – Jaypee