如何在 tkinter 中安排更新(f/e,更新时钟)?

编程入门 行业动态 更新时间:2024-10-11 15:21:58
本文介绍了如何在 tkinter 中安排更新(f/e,更新时钟)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 Python 的 tkinter 库编写程序.

I'm writing a program with Python's tkinter library.

我的主要问题是我不知道如何创建计时器或时钟,如hh:mm:ss.

My major problem is that I don't know how to create a timer or a clock like hh:mm:ss.

我需要它来自我更新(这是我不知道该怎么做的);当我在循环中使用 time.sleep() 时,整个 GUI 会冻结.

I need it to update itself (that's what I don't know how to do); when I use time.sleep() in a loop the whole GUI freezes.

推荐答案

Tkinter 根窗口有一个名为 after 的方法,可用于安排在给定时间段后调用的函数.如果该函数本身调用 after,则您已经设置了一个自动重复发生的事件.

Tkinter root windows have a method called after which can be used to schedule a function to be called after a given period of time. If that function itself calls after you've set up an automatically recurring event.

这是一个工作示例:

# for python 3.x use 'tkinter' rather than 'Tkinter' import Tkinter as tk import time class App(): def __init__(self): self.root = tk.Tk() self.label = tk.Label(text="") self.label.pack() self.update_clock() self.root.mainloop() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.root.after(1000, self.update_clock) app=App()

请记住,after 并不能保证函数会准时运行.它只安排作业在给定的时间后运行.由于 Tkinter 是单线程的,如果应用程序很忙,在调用它之前可能会有延迟.延迟通常以微秒为单位.

Bear in mind that after doesn't guarantee the function will run exactly on time. It only schedules the job to be run after a given amount of time. It the app is busy there may be a delay before it is called since Tkinter is single-threaded. The delay is typically measured in microseconds.

更多推荐

如何在 tkinter 中安排更新(f/e,更新时钟)?

本文发布于:2023-11-27 14:18:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638420.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时钟   如何在   tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!