如何使用tkinter创建计时器?

Die*_*tro 72 python user-interface tkinter

我需要使用Python的tkinter库编写程序代码.

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

我需要它来更新自己(这是我不知道该怎么做).

Bry*_*ley 108

Tkinter根窗口有一个方法after,可以用来调度在给定时间段后调用的函数.如果该函数本身调用after您已设置自动重复事件.

这是一个工作示例:

# 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()
Run Code Online (Sandbox Code Playgroud)

请记住,after不保证功能将准确按时运行.它只安排在给定时间后运行的作业.应用程序很忙,因为Tkinter是单线程的,所以在调用它之前可能会有一段延迟.延迟通常以微秒为单位.

  • @SatwikPasani:不,因为它不是递归调用。它只是将工作放在队列中。 (2认同)
  • @user924:`self.root.after(delay, func)`。 (2认同)

Dav*_*ole 10

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

#!/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()
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的答案,有一件重要的事情 - 显示的时间实际上是系统时间,而不是一些累积的错误时间(如果您等待“大约 1000 毫秒”60 次,您会得到“大约一分钟”而不是 60 秒,并且误差随着时间的推移而增大)。然而,您的时钟可能会在显示时跳过秒数,您可以累积亚秒误差,然后向前跳过 2 秒。我建议:`self.after(1000 - int(1000 * (time.time() - int(time.time())))) 或 1000, self.onUpdate)`。最好将 `time.time()` 保存到该表达式之前的变量中。 (2认同)
  • 我渴望变得很棒,可以将xkcd嵌入我的评论中:) (2认同)
  • 使用frame.after()而不是root.after()有什么好处? (2认同)

Rav*_*n D 6

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()
Run Code Online (Sandbox Code Playgroud)

  • 如果您可以添加一些说明会很有帮助。只是复制/粘贴代码很少有用;-) (5认同)
  • 这段代码给出了当地的确切时间。它也可以作为一个计时器。 (3认同)