Python桌面时钟代码示例 - 使用Tkinter库
Python桌面时钟代码示例
要编写一个桌面时钟,需要确定编程语言和操作系统。以下是一个使用Python编写的简单桌面时钟示例,使用Tkinter库创建GUI窗口和标签,并使用time库获取当前时间。
import tkinter as tk
import time
class Clock:
def __init__(self, root):
self.root = root
self.time_label = tk.Label(root, font=('calibri', 40, 'bold'), background='black', foreground='#42f5e8')
self.time_label.pack(anchor='center')
def update(self):
current_time = time.strftime('%H:%M:%S')
self.time_label.config(text=current_time)
self.root.after(1000, self.update)
if __name__ == '__main__':
root = tk.Tk()
root.title('Clock')
clock = Clock(root)
clock.update()
root.mainloop()
该程序中,update()方法每隔1秒钟更新一次时间显示。
代码说明:
- import tkinter as tk: 导入Tkinter库,用于创建GUI窗口和标签。
- import time: 导入time库,用于获取当前时间。
- class Clock: 定义一个Clock类,用于创建时钟对象。
- init(self, root): 初始化方法,创建时钟标签并设置样式。
- update(self): 更新方法,每隔1秒钟更新时间显示。
- root.after(1000, self.update): 使用
after方法,每隔1000毫秒(1秒)调用一次update方法。 - root.mainloop(): 启动Tkinter事件循环,保持窗口显示并响应用户操作。
原文地址: https://www.cveoy.top/t/topic/nil6 著作权归作者所有。请勿转载和采集!