以下是一个使用tkinter实现的电子时钟,可以显示时间和日期。鼠标点击时窗口会变为透明,没有标题栏,并且可以拖动窗口。
from tkinter import *
import time
class Clock:
def __init__(self, root):
self.root = root
self.root.title("电子时钟")
self.root.geometry("300x150")
# 设置窗口无标题栏
self.root.overrideredirect(True)
# 设置窗口背景透明
self.root.attributes("-alpha", 0.8)
# 鼠标事件绑定
self.root.bind("<ButtonPress-1>", self.start_move)
self.root.bind("<B1-Motion>", self.on_move)
# 显示时间和日期的标签
self.time_label = Label(self.root, font=("Helvetica", 48))
self.date_label = Label(self.root, font=("Helvetica", 14))
self.time_label.pack(pady=20)
self.date_label.pack()
self.update_clock()
def update_clock(self):
# 获取当前时间和日期
current_time = time.strftime("%H:%M:%S")
current_date = time.strftime("%Y-%m-%d")
# 更新标签的文本内容
self.time_label.config(text=current_time)
self.date_label.config(text=current_date)
# 每1秒更新一次时间
self.root.after(1000, self.update_clock)
def start_move(self, event):
# 记录鼠标点击位置
self.start_x = event.x
self.start_y = event.y
def on_move(self, event):
# 移动窗口位置
x = self.root.winfo_x() + (event.x - self.start_x)
y = self.root.winfo_y() + (event.y - self.start_y)
self.root.geometry("+%s+%s" % (x, y))
root = Tk()
clock = Clock(root)
root.mainloop()
你可以尝试运行以上代码,在屏幕上会显示一个电子时钟窗口。你可以拖动窗口改变位置,点击窗口时窗口会变为透明。