QTIMER事件不执行

发布于 2025-02-09 17:16:15 字数 552 浏览 0 评论 0原文

我正在尝试使用Python Timers的第一个播放,以与QT GUI一起使用,但是我创建的这个简单示例不是触发“ update_time”事件。按预期打印“开始”。

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer, QTime

def change_time(): 
        timer = QTimer()
        timer.timeout.connect(update_time)
        timer.start(1000)
        print("start")

def update_time():
        time = QTime.currentTime()
        #not executed
        print("executed")

if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
change_time()
sys.exit(app.exec_())

I'm trying my first play with Python timers for use with QT GUI's, but this simple example I have created is not triggering the 'update_time' event. 'start' is printed ok as expected.

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer, QTime

def change_time(): 
        timer = QTimer()
        timer.timeout.connect(update_time)
        timer.start(1000)
        print("start")

def update_time():
        time = QTime.currentTime()
        #not executed
        print("executed")

if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
change_time()
sys.exit(app.exec_())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遗弃M 2025-02-16 17:16:15

或者,除了@musicamante建议您还可以在函数之外定义计时器,以便如果您决定停止计时器,将来对change_time可以重复使用相同的计时器并避免创建新的计时器。

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer, QTime

def change_time(timer): 
    timer.timeout.connect(update_time)
    timer.start(1000)
    print("start")

def update_time():
    time = QTime.currentTime()
    #not executed
    print("executed")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    timer = QTimer()
    change_time(timer)
    sys.exit(app.exec_())

Alternatively to what @musicamante suggested you could also define the timer outside of the function so that if you ever decide to stop the timer, future calls to change_time can reuse the same timer and avoid creating a new one.

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer, QTime

def change_time(timer): 
    timer.timeout.connect(update_time)
    timer.start(1000)
    print("start")

def update_time():
    time = QTime.currentTime()
    #not executed
    print("executed")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    timer = QTimer()
    change_time(timer)
    sys.exit(app.exec_())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文