如何在 tkinter 中安排更新(f/e,更新时钟)? [英] How can I schedule updates (f/e, to update a clock) in tkinter?

查看:37
本文介绍了如何在 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,更新时钟)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆