最近写一个程序需要周期性执行任务,用pyqt中的Qtimer实现,查了网上的例程,写了一个测试程序验证Qtimer的功能。
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QTimer
import sys
def work():
print("hello world")
if __name__ == "__main__":
t = QTimer()
t.start(1000)
t.timeout.connect(work)
但是执行时会一直返回错误
QObject::startTimer: Timers can only be used with threads started with QThread
再次查阅了别人的例程后,改为:
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QTimer
import sys
def work():
print("hello world")
if __name__ == "__main__":
app = QApplication(sys.argv)
t = QTimer()
t.start(200)
t.timeout.connect(work)
sys.exit(app.exec_())
增加 app = QApplication(sys.argv) 和 sys.exit(app.exec_()) 这两句后,测试程序工作正常
"C:\Program Files\Python37\python.exe" D:/github/raisecom-itn-auto-upgrade/test-qtimer.py
hello world
hello world
hello world
hello world
hello world
hello world
hello world