python tkinder电子时钟 要求: (1)不显示标题栏,总是顶端显示,不被其他窗口覆盖; (2)实时显示日期和时间; (3)可以用鼠标左键按住拖动,在电子时钟上右击可以结束程序; (4)拖动时透明度变大,鼠标左键抬起时恢复半透明状态。
时间: 2024-05-29 20:12:20 浏览: 75
以下是实现上述要求的代码:
```python
import tkinter as tk
from datetime import datetime
class Clock(tk.Tk):
def __init__(self):
super().__init__()
self.overrideredirect(True) # 不显示标题栏
self.attributes('-topmost', True) # 总是置顶
self.geometry('+0+0') # 起始位置为屏幕左上角
self.alpha = 0.5 # 初始透明度
self.bind('<Button-1>', self.start_move)
self.bind('<ButtonRelease-1>', self.stop_move)
self.bind('<B3-Motion>', lambda event: self.destroy()) # 右击结束程序
self.label = tk.Label(self, font=('Arial', 50), fg='white', bg='black')
self.label.pack(expand=True, fill=tk.BOTH)
self.update_clock()
def start_move(self, event):
self.alpha = 0.8 # 拖动时透明度变大
self.attributes('-alpha', self.alpha)
self.start_x = event.x
self.start_y = event.y
def stop_move(self, event):
self.alpha = 0.5 # 鼠标左键抬起时恢复半透明状态
self.attributes('-alpha', self.alpha)
def update_clock(self):
now = datetime.now()
date_str = now.strftime('%Y-%m-%d')
time_str = now.strftime('%H:%M:%S')
self.label.config(text=f'{date_str}\n{time_str}')
self.after(1000, self.update_clock)
if __name__ == '__main__':
clock = Clock()
clock.mainloop()
```
运行效果如下图所示:
![clock](https://cdn.luogu.com.cn/upload/image_hosting/i1k4z4fh.png)
阅读全文