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是单线程的,所以在调用它之前可能会有一段延迟.延迟通常以微秒为单位.
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)
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)