如何在PyQt6中实现每隔若干毫秒自动调用函数?
PyQt6中实现定时调用函数的方法及控件移动问题修正
一、对应tkinter after()的QTimer用法
在PyQt6中,要实现每隔指定毫秒自动调用函数,需借助QTimer的timeout信号与start()方法,步骤如下:
- 将目标函数绑定到QTimer的
timeout信号(使用connect()方法) - 用
setInterval(毫秒数)设置触发间隔 - 调用
start()启动定时器,此后定时器会每隔指定毫秒自动触发绑定的函数
二、你的代码问题分析与修正
问题根源
你编写的move()函数中使用了while循环,这会直接阻塞PyQt的UI主线程——PyQt的界面更新、事件处理都依赖主线程,while会一次性把posx从0累加至50,整个过程中主线程完全被占用,根本没时间刷新控件的显示状态,所以你只看到变量值变化,控件却没移动。此外,循环内重复设置timer.setInterval(512)属于无效操作,定时器间隔只需设置一次。
修正后的代码
from PyQt6.QtWidgets import QWidget, QLabel, QApplication from PyQt6.QtCore import QTimer import sys posx = 0 posy = 0 label = None timer = None def move_label(): global posx, posy, label, timer if posx < 50: label.move(posx, posy) posx += 1 posy += 1 else: timer.stop() # 达到移动上限后停止定时器 if __name__ == "__main__": app = QApplication(sys.argv) window = QWidget() window.resize(200, 200) label = QLabel("测试标签", window) label.setStyleSheet("background-color: red;") timer = QTimer() timer.setInterval(512) # 设置512毫秒的触发间隔 timer.timeout.connect(move_label) # 绑定定时执行的函数 timer.start() # 启动定时器 window.show() sys.exit(app.exec())
修正说明
- 移除
while循环,改为每次move_label()被调用时仅执行一次移动操作 - 当
posx达到50时,调用timer.stop()终止定时器 - 定时器的
timeout信号每隔512毫秒触发一次,每次触发都会执行move_label(),这样UI主线程有足够时间处理界面刷新,控件就能正常移动
内容的提问来源于stack exchange,提问作者Samarth Chohan
相关产品推荐
相关产品推荐

