import tkinter as tk
import timeclass Clock:def __init__(self, root):self.root = rootself.root.overrideredirect(1) # 设置为无标题栏self.root.attributes('-alpha', 0.5) # 设置为半透明self.root.bind('<Button-1>', self.quit) # 点击窗口退出self.label_time = tk.Label(root, font=('calibri', 40, 'bold'), bg='black', fg='white')self.label_time.pack(padx=20, pady=20)self.label_date = tk.Label(root, font=('calibri', 20), bg='black', fg='white')self.label_date.pack(padx=20, pady=10)self.update_time()def update_time(self):current_time = time.strftime('%H:%M:%S')self.label_time.config(text=current_time)self.root.after(1000, self.update_time)def quit(self, event):self.root.destroy()root = tk.Tk()
clock = Clock(root)
root.mainloop()
该程序设置了一个Clock类,包含一个时间和日期标签以及一个循环更新时间的方法。在mainloop中实例化该类,然后运行Tkinter应用程序。
在初始化时,设置了一些窗口属性,如无标题栏和透明度。overrideredirect方法去除了窗口的标准标题栏,而attributes方法设置透明度,在这里设置为0.5。
时间和日期标签使用Label方法创建,并设置了一些标签属性,如字体,背景和前景颜色。update_time方法使用strftime方法获取当前时间,并将其显示在时间标签上。
最后,quit方法退出应用程序,单击窗口时调用该方法。