欢迎访问宙启技术站
智能推送

PyQt5.QtCore.QTimer实现定时任务的例子

发布时间:2024-01-06 04:03:03

PyQt5.QtCore.QTimer是一个用于定时触发事件的类,它可以在指定的时间间隔内重复执行某个函数或代码块。下面是一个使用PyQt5.QtCore.QTimer实现定时任务的例子,并附带一个使用例子。

例子:

import sys
from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtCore import QTimer

def update_label():
    label.setText("定时任务执行中...")

app = QApplication(sys.argv)

label = QLabel("点击按钮开始定时任务")
label.show()

# 创建定时器对象
timer = QTimer()
# 设置定时器的时间间隔,单位为毫秒
timer.setInterval(1000)
# 连接定时器的timeout信号到update_label函数
timer.timeout.connect(update_label)

def start_timer():
    # 开始定时器
    timer.start()

def stop_timer():
    # 停止定时器
    timer.stop()
    label.setText("定时任务已停止")

# 创建按钮对象
button_start = QPushButton("开始定时任务")
button_stop = QPushButton("停止定时任务")
# 连接按钮的clicked信号到对应的槽函数
button_start.clicked.connect(start_timer)
button_stop.clicked.connect(stop_timer)
# 显示按钮
button_start.show()
button_stop.show()

sys.exit(app.exec_())

这个例子中,我们创建了一个简单的GUI应用程序,包含一个标签和两个按钮。点击"开始定时任务"按钮后,定时器会每隔1秒调用一次update_label函数,使标签的文本更新为"定时任务执行中..."。点击"停止定时任务"按钮后,定时器会停止调用update_label函数,并将标签的文本更新为"定时任务已停止"。