【python_在桌面生成一个时间标签】

在桌面生成一个时间标签,放到屏幕左上角。

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()
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值