""" 桌面提醒工具模块 在任务开始前于桌面弹出置顶警告窗口并倒计时, 倒计时结束后窗口自动关闭,程序继续执行 """ import tkinter as tk from . import get_logger log = get_logger("notify") def show_warning_countdown( message: str = "即将开始自动截图", seconds: int = 5, title: str = "警告", ): """ 在桌面弹出置顶警告窗口并倒计时,结束后自动关闭 倒计时期间函数阻塞,结束后窗口销毁并返回,任务继续执行。 Args: message: 警告正文 seconds: 倒计时秒数(<=0 时直接返回) title: 警告标题 """ if seconds <= 0: return try: root = tk.Tk() except Exception as e: # tkinter 初始化失败(如无显示环境)时仅记录日志,不阻塞任务 log.warning("无法弹出桌面警告窗口: %s", e) return root.title(title) root.attributes("-topmost", True) # 始终置顶,确保用户能看到 root.resizable(False, False) bg = "#c62828" # 红色警示背景 root.configure(bg=bg) # 标题 tk.Label( root, text=f"—— {title} ——", font=("Microsoft YaHei UI", 32, "bold"), fg="white", bg=bg, ).pack(padx=80, pady=(30, 10)) # 正文 tk.Label( root, text=message, font=("Microsoft YaHei UI", 20), fg="white", bg=bg, ).pack(padx=80, pady=5) # 倒计时(每秒刷新) countdown = tk.Label( root, text="", font=("Microsoft YaHei UI", 48, "bold"), fg="#ffeb3b", bg=bg, ) countdown.pack(padx=80, pady=15) # 底部提示 tk.Label( root, text="倒计时结束后任务自动开始,请勿操作鼠标键盘", font=("Microsoft YaHei UI", 12), fg="#ffebee", bg=bg, ).pack(padx=80, pady=(0, 30)) # 窗口居中显示 root.update_idletasks() w, h = root.winfo_width(), root.winfo_height() sw, sh = root.winfo_screenwidth(), root.winfo_screenheight() root.geometry(f"+{(sw - w) // 2}+{(sh - h) // 2}") def _tick(remaining: int): if remaining > 0: countdown.config(text=f"{remaining} 秒后开始") root.after(1000, _tick, remaining - 1) else: root.destroy() log.info("桌面警告已弹出: '%s:%s',倒计时 %d 秒", title, message, seconds) root.after(100, _tick, seconds) root.mainloop() log.info("倒计时结束,窗口已关闭,任务继续")