我正在用Python的tkinter库编写一个程序。
我的主要问题是,我不知道如何创建一个计时器或时钟,如hh:mm:ss
。
我需要它来自我更新(这是我不知道该怎么做的);当我在一个循环中使用time.sleep()
时,整个图形用户界面都会冻结。
发布于 2010-03-08 20:20:03
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()
请记住,after
并不能保证函数会准时运行。它只安排作业在给定的时间量之后运行。如果应用程序很忙,那么在调用它之前可能会有延迟,因为Tkinter是单线程的。延迟通常以微秒为单位测量。
发布于 2015-12-01 22:21:50
使用frame.after()而不是顶级应用程序的Python3时钟示例。还显示了如何使用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()
发布于 2017-09-26 21:02:57
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()
https://stackoverflow.com/questions/2400262
复制相似问题