编写程序,实现如下图所示的电子时钟。要求: (1)不显示标题栏,总是顶端显示,不被其他窗口覆盖; (2)实时显示日期和时间; (3)可以用鼠标左键按住拖动,在电子时钟上右击可以结束程序; (4)拖动时透明度变大,鼠标左键抬起时恢复半透明状态
时间: 2024-05-21 22:10:30 浏览: 71
用代码实现电子时钟
import tkinter as tk
import time
class Clock:
def __init__(self, master):
self.master = master
self.master.overrideredirect(True) # 不显示标题栏
self.master.attributes("-topmost", True) # 总是顶端显示,不被其他窗口覆盖
self.master.bind('<Button-1>', self.onStart) # 鼠标左键按住拖动
self.master.bind('<B1-Motion>', self.onMove)
self.master.bind('<ButtonRelease-1>', self.onStop)
self.master.bind('<Button-3>', self.onExit) # 在电子时钟上右击可以结束程序
self.master.bind('<Escape>', self.onExit) # 按 Esc 也可以结束程序
self.master.bind('<FocusOut>', self.onFocusOut) # 窗口失去焦点时恢复半透明状态
self.master.bind('<FocusIn>', self.onFocusIn) # 窗口获得焦点时恢复半透明状态
self.alpha = 0.5 # 初始透明度
self.label_date = tk.Label(self.master, text='', font=('Arial', 12))
self.label_time = tk.Label(self.master, text='', font=('Arial', 36))
self.label_date.pack(side=tk.TOP)
self.label_time.pack(side=tk.TOP)
self.update()
def update(self):
# 实时显示日期和时间
self.label_date.config(text=time.strftime('%Y-%m-%d'))
self.label_time.config(text=time.strftime('%H:%M:%S'))
self.master.after(1000, self.update)
def onStart(self, event):
self.startX = event.x
self.startY = event.y
self.alpha = 1.0 # 拖动时透明度变大
def onMove(self, event):
self.master.geometry('+{0}+{1}'.format(event.x_root - self.startX, event.y_root - self.startY))
self.master.attributes("-alpha", self.alpha)
def onStop(self, event):
self.alpha = 0.5 # 鼠标左键抬起时恢复半透明状态
def onExit(self, event):
self.master.destroy()
def onFocusOut(self, event):
self.master.attributes("-alpha", 0.5) # 窗口失去焦点时恢复半透明状态
def onFocusIn(self, event):
self.master.attributes("-alpha", self.alpha) # 窗口获得焦点时恢复透明度
if __name__ == '__main__':
root = tk.Tk()
clock = Clock(root)
root.mainloop()
阅读全文