python tkinter 倒计时

import tkinter as tk
import time
from LeaveTime import get_count_down_seconds

class CountdownApp:
    def __init__(self, root, countdown_seconds=10):
        self.root = root
        self.countdown_seconds = countdown_seconds

        # 设置无边框窗口
        self.root.overrideredirect(True)

        # 设置窗口大小和位置
        window_width = 60
        window_height = 30
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        x = (screen_width - window_width )
        y = (screen_height - window_height )
        self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")

        # 设置窗口透明度 (这里设为 0.7)
        self.root.attributes("-alpha", 0.7)
        # 设置窗口始终置顶
        root.attributes("-topmost", True)

        # 设置背景颜色
        self.root.configure(bg="#2e2e2e")

        # 拖动窗口所需变量
        self.offset_x = 0
        self.offset_y = 0

        # 显示倒计时文本
        self.label = tk.Label(root, text="", font=("Arial", 10), bg="#2e2e2e", fg="white")
        self.label.pack(expand=True)

        # 绑定鼠标事件用于拖动窗口
        self.root.bind("<ButtonPress-1>", self.start_move)
        self.root.bind("<B1-Motion>", self.do_move)
        self.root.bind("<Button-3>", lambda e: root.destroy())

        # 启动倒计时
        self.update_countdown()

    def start_move(self, event):
        self.offset_x = event.x
        self.offset_y = event.y

    def do_move(self, event):
        x = self.root.winfo_pointerx() - self.offset_x
        y = self.root.winfo_pointery() - self.offset_y
        self.root.geometry(f"+{x}+{y}")

    def update_countdown(self):
        def seconds_to_HMS(seconds):
            hours = seconds // 3600
            minutes = (seconds % 3600) // 60
            seconds = seconds % 60
            return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
        if self.countdown_seconds >= 0:
            self.label.config(text=seconds_to_HMS(self.countdown_seconds))
            self.countdown_seconds -= 1
            self.root.after(1000, self.update_countdown)
        else:
            self.label.config(text="时间到!")
            # 可选:自动关闭窗口
            self.root.after(2000, self.root.destroy())

if __name__ == "__main__":
    root = tk.Tk()
    app = CountdownApp(root, countdown_seconds=get_count_down_seconds())
    root.mainloop()
文章目录