在桌面生成一个时间标签,放到屏幕左上角。
import tkinter as tk
from datetime import datetime
def update_time():
# 获取当前时间
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 更新标签的内容
time_label.config(text=current_time)
# 每1000毫秒(1秒)更新一次时间
root.after(1000, update_time)
# # 创建主窗口
root = tk.Tk()
# 设置窗口标题
# root.title("实时时间戳")
root.overrideredirect(True) # 去掉标题栏
# 设置窗口大小
root.geometry("220x21")
# 使窗口始终位于最前面
root.attributes('-topmost', True)
# 创建一个标签用于显示时间
time_label = tk.Label(root, font=('Arial', 18), bg='black', fg='white')
# 将标签放置在窗口左上角
time_label.pack(side=tk.TOP, anchor=tk.NW, padx=0, pady=0)
# 调用函数开始更新时间
update_time()
# 进入消息循环
root.mainloop()
希望可以随意拖动
import tkinter as tk
from datetime import datetime
def update_time():
# 获取当前时间
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 更新标签的内容
time_label.config(text=current_time)
# 每1000毫秒(1秒)更新一次时间
root.after(1000, update_time)
def start_move(event):
# 当鼠标按下时,记录鼠标当前位置
global last_x, last_y
last_x = event.x
last_y = event.y
def move_window(event):
# 根据鼠标移动的距离移动窗口
x = root.winfo_pointerx() - last_x
y = root.winfo_pointery() - last_y
root.geometry('+{0}+{1}'.format(x, y))
def on_double_click(event):
# 阻止双击时的默认行为
return "break"
# 创建主窗口
root = tk.Tk()
# 设置窗口标题
# root.title("实时时间戳")
root.overrideredirect(True) # 去掉标题栏
# 设置窗口大小
root.geometry("220x21")
# 使窗口始终位于最前面
root.attributes('-topmost', True)
# 创建一个标签用于显示时间
time_label = tk.Label(root, font=('Arial', 18), bg='black', fg='white')
# 将标签放置在窗口左上角
time_label.pack(side=tk.TOP, anchor=tk.NW, padx=0, pady=0)
# 绑定鼠标点击事件
root.bind('<Button-1>', start_move)
# 绑定鼠标移动事件
root.bind('<B1-Motion>', move_window)
# 绑定双击事件
root.bind('<Double-Button-1>', on_double_click)
# 调用函数开始更新时间
update_time()
# 进入消息循环
root.mainloop()