首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在tkinter中安排更新(f/e,更新时钟)?

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

Stack Overflow用户
提问于 2010-03-08 17:16:35
回答 7查看 134.4K关注 0票数 85

我正在用Python的tkinter库编写一个程序。

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

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

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-03-08 20:20:03

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

下面是一个有效的示例:

代码语言:javascript
复制
# 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是单线程的。延迟通常以微秒为单位测量。

票数 135
EN

Stack Overflow用户

发布于 2015-12-01 22:21:50

使用frame.after()而不是顶级应用程序的Python3时钟示例。还显示了如何使用StringVar()更新标签

代码语言:javascript
复制
#!/usr/bin/env python3

# Display UTC.
# started with https://docs.python.org/3.4/library/tkinter.html#module-tkinter

import tkinter as tk
import time

def current_iso8601():
    """Get current date and time in ISO8601"""
    # https://en.wikipedia.org/wiki/ISO_8601
    # https://xkcd.com/1179/
    return time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.now = tk.StringVar()
        self.time = tk.Label(self, font=('Helvetica', 24))
        self.time.pack(side="top")
        self.time["textvariable"] = self.now

        self.QUIT = tk.Button(self, text="QUIT", fg="red",
                                            command=root.destroy)
        self.QUIT.pack(side="bottom")

        # initial time display
        self.onUpdate()

    def onUpdate(self):
        # update displayed time
        self.now.set(current_iso8601())
        # schedule timer to call myself after 1 second
        self.after(1000, self.onUpdate)

root = tk.Tk()
app = Application(master=root)
root.mainloop()
票数 12
EN

Stack Overflow用户

发布于 2017-09-26 21:02:57

代码语言:javascript
复制
from tkinter import *
import time
tk=Tk()
def clock():
    t=time.strftime('%I:%M:%S',time.localtime())
    if t!='':
        label1.config(text=t,font='times 25')
    tk.after(100,clock)
label1=Label(tk,justify='center')
label1.pack()
clock()
tk.mainloop()
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2400262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档