小孩玩电脑没有时间概念,所以用AI弄了这个定时锁屏软件,点击开始之后窗口会自动隐藏,只能通过快捷键Ctal+Alt+N+M调出窗口,倒计时还有10秒的时间,会弹窗提示

点此下载

电脑定时锁屏软件V1.0

 

 

 

    # 设置窗口图标
    try:
        if hasattr(sys, '_MEIPASS'):
            icon_path = os.path.join(sys._MEIPASS, 'icon.ico')
        else:
            icon_path = 'icon.ico'
        if os.path.exists(icon_path):
            self.root.iconbitmap(icon_path)
    except Exception:
        # 如果图标不存在或无法加载,忽略错误
        pass
    # 设置主题颜色 - 使用微信绿
    self.bg_color = "#f0f0f0"
    self.btn_color = "#07C160"  # 微信绿
    self.btn_hover_color = "#06984e"  # 微信绿-深
    self.text_color = "#333333"
    self.root.configure(bg=self.bg_color)

    # 初始化变量
    self.lock_timer = None
    self.is_timer_running = False
    self.remaining_time = 0
    self.paused_time = 0
    self.is_paused = False
    self.last_error = None

    # 初始化窗口位置记忆
    self.last_window_position = None

    # 创建GUI组件
    self.create_widgets()

    # 设置全局热键
    self.set_hotkey()

    # 创建系统托盘图标
    self.create_tray_icon()

def create_widgets(self):
    main_frame = ttk.Frame(self.root, padding="20")
    main_frame.pack(fill=tk.BOTH, expand=True)
    main_frame.configure(style="Main.TFrame")

    style = ttk.Style()
    style.configure("Main.TFrame", background=self.bg_color)
    style.configure("TLabel", background=self.bg_color, foreground=self.text_color)
    style.configure("Title.TLabel", font=("SimHei", 16, "bold"), background=self.bg_color, foreground=self.text_color)
    style.configure("Subtitle.TLabel", font=("SimHei", 10), background=self.bg_color, foreground="#666666")
    style.configure("Status.TLabel", font=("SimHei", 10), background=self.bg_color, foreground=self.text_color)
    style.configure("Hotkey.TLabel", font=("SimHei", 8), foreground="#666666", background=self.bg_color)
    style.configure("TButton", font=("SimHei", 10))

    title_frame = ttk.Frame(main_frame)
    title_frame.pack(fill=tk.X, pady=(0, 15))
    title_frame.configure(style="Main.TFrame")

    title_label = ttk.Label(title_frame, text="电脑锁屏助手", style="Title.TLabel")
    title_label.pack(side=tk.LEFT)

    def create_custom_button(parent, text, command, width=5):
        btn = tk.Button(
            parent, 
            text=text, 
            font=("SimHei", 11, "bold"),
            bg=self.btn_color,
            fg="white",
            activebackground=self.btn_hover_color,
            activeforeground="white",
            relief=tk.RAISED,
            bd=0,
            highlightthickness=0,
            padx=10,
            pady=10,
            width=width,
            command=command
        )
        btn.configure(highlightbackground=self.btn_color, highlightcolor=self.btn_color, highlightthickness=0)
        btn.bind("<Enter>", lambda e, b=btn: b.config(bg=self.btn_hover_color))
        btn.bind("<Leave>", lambda e, b=btn: b.config(bg=self.btn_color))
        btn.bind("<ButtonPress-1>", lambda e, b=btn: b.config(bg="#004080"))
        btn.bind("<ButtonRelease-1>", lambda e, b=btn: b.config(bg=self.btn_hover_color))
        return btn

    # 时间选择器区域 - 放在上面一行
    time_select_frame = ttk.Frame(main_frame)
    time_select_frame.pack(fill=tk.X, pady=15)
    time_select_frame.configure(style="Main.TFrame")

    # 5分钟按钮
    self.btn_5min = create_custom_button(time_select_frame, "5分钟", lambda: self.start_timer(5), width=3)
    self.btn_5min.pack(side=tk.LEFT, padx=10, pady=5)

    # 10分钟按钮
    self.btn_10min = create_custom_button(time_select_frame, "10分钟", lambda: self.start_timer(10), width=4)
    self.btn_10min.pack(side=tk.LEFT, padx=10, pady=5)

    # 自定义时间输入区域
    custom_frame = ttk.Frame(time_select_frame)
    custom_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=10)
    custom_frame.configure(style="Main.TFrame")

    self.custom_time_var = tk.StringVar()
    self.custom_time_entry = ttk.Entry(
        custom_frame, 
        textvariable=self.custom_time_var,
        width=4,
        font=(("SimHei", 22))
    )
    self.custom_time_entry.pack(side=tk.LEFT, padx=(0, 5), pady=2)
    self.custom_time_entry.bind("<KeyRelease>", self.validate_time_input)
    self.custom_time_entry.bind("<Return>", lambda event: self.start_custom_timer())

    ttk.Label(custom_frame, text="分钟", font=(("SimHei", 20))).pack(side=tk.LEFT, padx=2)

    # 按钮操作区域 - 放在下面一行
    action_frame = ttk.Frame(main_frame)
    action_frame.pack(fill=tk.X, pady=10)
    action_frame.configure(style="Main.TFrame")

    # 开始按钮
    self.btn_start = create_custom_button(action_frame, "开始", self.start_custom_timer, width=6)
    self.btn_start.pack(side=tk.LEFT, padx=10, pady=5)

    # 暂停/继续按钮
    self.btn_pause = create_custom_button(action_frame, "暂停/继续", self.toggle_pause, width=8)
    self.btn_pause.pack(side=tk.LEFT, padx=10, pady=5)

    # 新增清空按钮
    self.btn_clear = create_custom_button(action_frame, "清空", self.cancel_timer, width=6)
    self.btn_clear.pack(side=tk.LEFT, padx=10, pady=5)

    status_frame = ttk.Frame(main_frame)
    status_frame.pack(fill=tk.X, pady=15)
    status_frame.configure(style="Main.TFrame")

    ttk.Label(status_frame, text="状态:", style="TLabel").pack(side=tk.LEFT)
    self.status_var = tk.StringVar()
    self.status_var.set("就绪")
    self.status_label = ttk.Label(status_frame, textvariable=self.status_var, style="Status.TLabel")
    self.status_label.pack(side=tk.LEFT, padx=5)

    bottom_frame = ttk.Frame(main_frame)
    bottom_frame.pack(fill=tk.X, side=tk.BOTTOM)
    bottom_frame.configure(style="Main.TFrame")

    hotkey_label = ttk.Label(bottom_frame, text="Ctrl+Alt+N+M 调出窗口", style="Hotkey.TLabel")
    hotkey_label.pack(pady=(10, 0))

def start_timer(self, minutes):
    """启动倒计时计时器"""
    try:
        if self.is_timer_running:
            # 取消当前计时器
            self.cancel_timer()

        # 设置新的倒计时时间
        self.remaining_time = minutes * 60
        self.is_timer_running = True
        self.is_paused = False

        # 更新状态
        self.status_var.set(f"锁屏将在 {minutes} 分钟后启动")
        self.update_tray_tooltip(f"锁屏将在 {minutes} 分钟后启动")

        # 记录启动事件
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"计时器启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, 设定时间: {minutes}分钟\n")

        # 创建并启动计时器线程
        self.lock_timer = threading.Thread(target=self.countdown)
        self.lock_timer.daemon = True
        self.lock_timer.start()

        # 隐藏窗口
        self.hide_window()
    except Exception as e:
        # 记录启动错误
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"启动计时器错误: {str(e)}\n")
        messagebox.showerror("错误", f"启动计时器时出错: {str(e)}")

def validate_time_input(self, event=None):
    """验证时间输入,只允许数字和小数点,最多480分钟"""
    input_text = self.custom_time_var.get()

    # 移除非数字和小数点的字符
    new_text = ''.join(c for c in input_text if c.isdigit() or c == '.')

    # 确保只有一个小数点
    if new_text.count('.') > 1:
        parts = new_text.split('.')
        new_text = parts[0] + '.' + ''.join(parts[1:])

    # 更新输入框
    if new_text != input_text:
        self.custom_time_var.set(new_text)
        # 保持光标位置
        pos = event.widget.index(tk.INSERT)
        event.widget.icursor(pos - (len(input_text) - len(new_text)))

    # 检查是否超过480分钟(8小时)
    try:
        if new_text:
            minutes = float(new_text)
            if minutes > 480:
                self.custom_time_var.set('480')
                self.status_var.set("警告: 超过最大时间限制")
            else:
                self.status_var.set("就绪")
    except ValueError:
        pass

def start_custom_timer(self):
    """从输入框启动自定义时间计时"""
    try:
        time_str = self.custom_time_var.get()
        if not time_str:
            messagebox.showwarning("输入错误", "请输入时间")
            return

        minutes = float(time_str)
        if minutes <= 0:
            messagebox.showwarning("输入错误", "请输入大于0的时间")
            return

        if minutes > 480:
            messagebox.showwarning("输入错误", "最大时间为480分钟")
            return

        # 保留浮点数,但设置最小时间为0.1分钟(6秒)
        if minutes < 0.1:
            minutes = 0.1  # 最少0.1分钟

        self.start_timer(minutes)
    except ValueError:
        messagebox.showwarning("输入错误", "请输入有效的数字")
        self.custom_time_entry.focus_set()

def toggle_pause(self):
    """暂停或恢复计时器"""
    if not self.is_timer_running:
        messagebox.showinfo("提示", "计时器未运行")
        return

    if self.is_paused:
        # 恢复计时器
        self.is_paused = False
        self.btn_pause.config(text="暂停/继续")
        self.btn_pause.config(bg=self.btn_color, fg="white", activebackground=self.btn_hover_color)
        time_text = self.format_time(self.remaining_time)
        self.status_var.set(f"恢复倒计时,剩余时间: {time_text}")
        self.update_tray_tooltip(f"恢复倒计时: {time_text}")
        # 继续倒计时线程
        self.lock_timer = threading.Thread(target=self.countdown)
        self.lock_timer.daemon = True
        self.lock_timer.start()
        # 记录恢复事件
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"计时器恢复时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, 剩余时间: {time_text}\n")
    else:
        # 暂停计时器
        self.is_paused = True
        self.btn_pause.config(text="继续")
        self.btn_pause.config(bg="#ffc107", fg="#333333", activebackground="#e0a800")
        time_text = self.format_time(self.remaining_time)
        self.status_var.set(f"已暂停,剩余时间: {time_text}")
        self.update_tray_tooltip(f"已暂停: {time_text}")
        # 记录暂停事件
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"计时器暂停时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, 剩余时间: {time_text}\n")

def countdown(self):
    """倒计时线程函数"""
    try:
        # 记录倒计时开始
        start_time = time.time()
        target_time = start_time + self.remaining_time
        # 清除可能存在的警告窗口引用
        if hasattr(self, '_warning_window'):
            if self._warning_window.winfo_exists():
                self._warning_window.destroy()

        while self.is_timer_running and not self.is_paused:
            # 计算剩余时间(更准确的计时方式)
            current_time = time.time()
            self.remaining_time = int(target_time - current_time)

            if self.remaining_time <= 0:
                break

            # 更新状态和托盘提示
            time_text = self.format_time(self.remaining_time)

            # 使用线程安全的方式更新GUI
            self.root.after(0, lambda tt=time_text: self.status_var.set(f"剩余时间: {tt}"))
            self.update_tray_tooltip(f"剩余时间: {time_text}")

            # 添加倒计时提示功能(10秒及以内)
            if 0 < self.remaining_time <= 10:
                # 使用线程安全的方式显示或更新提示框
                self.root.after(0, lambda remaining=self.remaining_time: self._show_lock_warning(remaining))

            # 休眠1秒,但可以被中断
            for _ in range(10):  # 分成10次小休眠,以便更快响应暂停/取消
                if not self.is_timer_running or self.is_paused:
                    break
                time.sleep(0.1)

            # 检查是否被暂停或取消
            if not self.is_timer_running or self.is_paused:
                break

        # 倒计时结束,执行锁屏
        if self.remaining_time <= 0 and self.is_timer_running and not self.is_paused:
            self.lock_screen()
    except Exception as e:
        # 记录倒计时错误
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"倒计时错误: {str(e)}\n")
        # 尝试锁屏作为安全措施
        try:
            self.lock_screen()
        except:
            pass

def format_time(self, seconds):
    """格式化时间为分:秒"""
    minutes = seconds // 60
    secs = seconds % 60
    return f"{minutes:02d}:{secs:02d}"

def _show_lock_warning(self, remaining):
    """显示锁屏前的警告提示,支持动态更新倒计时"""
    # 检查是否已存在警告窗口,如果存在则更新内容,否则创建新窗口
    if hasattr(self, '_warning_window') and self._warning_window.winfo_exists():
        # 更新现有窗口的标签文本
        if hasattr(self, '_warning_label'):
            self._warning_label.config(text=f"电脑还有 {remaining} 秒锁屏了")
    else:
        # 创建一个独立的提示窗口
        self._warning_window = tk.Toplevel(self.root)
        self._warning_window.title("锁屏警告")
        self._warning_window.geometry("300x150")
        self._warning_window.attributes("-topmost", True)
        self._warning_window.configure(bg="#f0f0f0")

        # 居中窗口
        self._warning_window.update_idletasks()
        width = self._warning_window.winfo_width()
        height = self._warning_window.winfo_height()
        x = (self._warning_window.winfo_screenwidth() // 2) - (width // 2)
        y = (self._warning_window.winfo_screenheight() // 2) - (height // 2)
        self._warning_window.geometry(f"{width}x{height}+{x}+{y}")

        # 添加提示标签
        self._warning_label = tk.Label(
            self._warning_window, 
            text=f"电脑还有 {remaining} 秒锁屏了", 
            font=("SimHei", 16, "bold"),
            bg="#f0f0f0",
            fg="#ff0000"
        )
        self._warning_label.pack(pady=20)

        # 添加关闭按钮
        btn_ok = tk.Button(
            self._warning_window, 
            text="知道了", 
            font=("SimHei", 12),
            bg=self.btn_color,
            fg="white",
            activebackground=self.btn_hover_color,
            relief=tk.RAISED,
            bd=0,
            padx=20,
            pady=8,
            command=self._warning_window.destroy
        )
        btn_ok.pack(pady=10)
        btn_ok.configure(highlightbackground=self.btn_color, highlightthickness=0)

def lock_screen(self):
    """锁定屏幕(支持多种锁屏方式作为备选)"""
    try:
        # 记录锁屏时间
        lock_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"屏幕锁定时间: {lock_time}\n")

        # 方法1: 使用Windows API (首选方法)
        try:
            result = ctypes.windll.user32.LockWorkStation()
            if result:
                with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
                    f.write("锁屏成功: 使用Windows API\n")
            else:
                raise Exception("LockWorkStation API 调用失败")
        except Exception as e1:
            # 记录首选方法失败
            with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
                f.write(f"首选锁屏方法失败: {str(e1)}\n")

            # 方法2: 使用rundll32命令
            try:
                import subprocess
                subprocess.run(["rundll32.exe", "user32.dll,LockWorkStation"], 
                              shell=True, check=True)
                with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
                    f.write("锁屏成功: 使用rundll32命令\n")
            except Exception as e2:
                # 记录方法2失败
                with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
                    f.write(f"备用锁屏方法失败: {str(e2)}\n")

                # 方法3: 使用PowerShell命令
                try:
                    import subprocess
                    powershell_command = "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait('^({ESC}{TAB}{ESC})')"
                    subprocess.run(["powershell.exe", "-Command", powershell_command], 
                                  shell=True, check=True)
                    with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
                        f.write("锁屏成功: 使用PowerShell命令\n")
                except Exception as e3:
                    # 所有方法都失败
                    with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
                        f.write(f"所有锁屏方法都失败: {str(e3)}\n")

                    # 显示消息提示用户手动锁屏
                    messagebox.showwarning(
                        "锁屏失败",
                        "无法自动锁定屏幕。请手动锁定您的计算机。\n" +
                        "锁屏时间: " + lock_time
                    )

        # 重置状态
        self.reset_timer()

    except Exception as e:
        # 记录总错误
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"锁屏过程总错误: {str(e)}\n")

        # 即使出错也要重置状态
        self.reset_timer()

def reset_timer(self):
    """重置计时器状态"""
    self.is_timer_running = False
    self.is_paused = False
    self.remaining_time = 0
    self.btn_pause.config(text="暂停")
    self.status_var.set("就绪")
    self.update_tray_tooltip("就绪")

def cancel_timer(self):
    """取消当前计时器"""
    # 确保线程安全地停止
    self.is_timer_running = False
    self.is_paused = False
    self.remaining_time = 0

    # 重置UI状态
    self.btn_pause.config(text="暂停")
    self.status_var.set("就绪")
    self.update_tray_tooltip("就绪")

    # 如果有正在运行的计时器线程,尝试让它自然结束
    # 注意:Python中不能强制终止线程,而是通过标志位让它自己退出

    # 额外确保界面可见,用户能看到取消后的状态
    self.show_window()

    # 记录取消事件
    try:
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"计时器取消时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
    except Exception as e:
        # 即使日志写入失败,也要确保功能正常
        pass

def hide_window(self):
    """隐藏窗口"""
    # 保存当前窗口位置
    try:
        x = self.root.winfo_x()
        y = self.root.winfo_y()
        if x > 0 and y > 0:  # 确保位置有效
            self.last_window_position = (x, y)
    except:
        pass  # 忽略获取位置时的错误

    # 完全隐藏窗口(不仅是最小化)
    self.root.withdraw()
    # 在系统托盘显示消息
    try:
        self.tray_icon.showmessage(
            "锁屏助手",
            "程序已在后台运行\n按 Ctrl+Alt+N+M 调出窗口",
            timeout=5000
        )
    except:
        pass  # 忽略托盘错误

def show_window(self):
    """显示窗口"""
    try:
        # 从隐藏状态恢复
        self.root.deiconify()
        # 确保窗口在最上层
        self.root.attributes("-topmost", True)
        self.root.attributes("-topmost", False)  # 允许其他窗口也能成为顶层
        # 激活窗口
        self.root.focus_force()

        # 检查是否有保存的窗口位置,如果没有则居中显示
        if not hasattr(self, 'last_window_position'):
            # 计算屏幕中心位置
            screen_width = self.root.winfo_screenwidth()
            screen_height = self.root.winfo_screenheight()
            window_width = 400  # 窗口宽度
            window_height = 350  # 窗口高度

            x = (screen_width - window_width) // 2
            y = (screen_height - window_height) // 2

            # 设置窗口位置并保存
            self.root.geometry(f"+{x}+{y}")
            self.last_window_position = (x, y)
        else:
            # 使用之前保存的位置
            x, y = self.last_window_position
            self.root.geometry(f"+{x}+{y}")
    except Exception as e:
        # 记录错误但不显示,避免影响用户体验
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"显示窗口错误: {str(e)}\n")

def create_tray_icon(self):
    """创建系统托盘图标"""
    try:
        # 尝试导入并创建系统托盘图标
        import pystray
        from pystray import MenuItem as item
        from PIL import Image, ImageDraw

        # 创建一个简单的图标
        def create_image():
            width = 64
            height = 64
            color1 = "#0078d7"
            color2 = "white"

            # 创建空白图像
            image = Image.new('RGB', (width, height), color1)
            dc = ImageDraw.Draw(image)

            # 绘制简单的锁图标
            dc.rectangle([10, 25, 54, 45], fill=color2)
            dc.rectangle([25, 15, 39, 35], fill=color2)
            dc.ellipse([20, 10, 44, 20], fill=color1, outline=color2, width=3)

            return image

        # 创建菜单
        menu = (
            item('显示窗口', self.show_window),
            item('暂停/恢复', self.toggle_pause),
            item('退出', self.on_closing)
        )

        # 创建托盘图标
        self.tray_icon = pystray.Icon("LockScreen", create_image(), "锁屏助手", menu)

        # 在单独的线程中运行托盘图标
        self.tray_thread = threading.Thread(target=self.tray_icon.run, daemon=True)
        self.tray_thread.start()
    except ImportError:
        # 如果没有安装pystray,使用tkinter的简化方法
        self.tray_icon = None
        pass

def update_tray_tooltip(self, message):
    """更新系统托盘提示文本"""
    try:
        if hasattr(self, 'tray_icon') and self.tray_icon:
            self.tray_icon.title = f"锁屏助手 - {message}"
    except:
        pass  # 忽略托盘错误

def set_hotkey(self):
    """设置全局热键"""
    try:
        # 移除可能已存在的热键(避免重复设置)
        try:
            keyboard.remove_hotkey('ctrl+alt+n+m')
        except:
            pass

        # 设置组合热键 Ctrl+Alt+N+M
        keyboard.add_hotkey('ctrl+alt+n+m', self.show_window)

        # 记录热键设置成功
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"热键设置成功: Ctrl+Alt+N+M\n")

    except Exception as e:
        # 记录错误
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"热键设置失败: {str(e)}\n")

        # 尝试使用备用方案
        try:
            # 备用方案:使用全局钩子监听按键事件
            def on_key_event(event):
                # 检查是否按下了Ctrl+Alt+N+M组合键
                if event.name == 'm' and keyboard.is_pressed('ctrl') and keyboard.is_pressed('alt') and keyboard.is_pressed('n'):
                    self.show_window()

            # 监听所有按键事件
            keyboard.on_press(on_key_event)

            # 记录备用方案设置成功
            with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
                f.write("备用热键方案设置成功\n")

        except Exception as e2:
            # 记录备用方案失败
            with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
                f.write(f"备用热键方案设置失败: {str(e2)}\n")

            # 显示警告消息
            messagebox.showwarning(
                "热键设置警告", 
                "无法设置全局热键。请确保以管理员权限运行程序。\n" +
                "您仍然可以通过系统托盘图标访问程序。"
            )

def on_closing(self):
    """窗口关闭事件处理"""
    # 取消计时器
    self.cancel_timer()
    # 清理热键
    try:
        keyboard.unhook_all()
    except:
        pass
    # 关闭托盘图标
    try:
        if hasattr(self, 'tray_icon') and self.tray_icon:
            self.tray_icon.stop()
    except:
        pass
    # 记录程序退出
    with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
        f.write(f"程序退出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        f.write("="*50 + "\n")
    # 关闭窗口
    self.root.destroy()

def check_environment(self):
    """检查运行环境"""
    try:
        # 创建日志目录(如果不存在)
        log_file = "lock_screen_log.txt"

        # 写入程序启动信息
        with open(log_file, "a", encoding="utf-8") as f:
            f.write("="*50 + "\n")
            f.write(f"程序启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"Python版本: {sys.version}\n")
            f.write(f"操作系统: Windows\n")

        # 检查是否以管理员权限运行
        try:
            is_admin = ctypes.windll.shell32.IsUserAnAdmin()
            with open(log_file, "a", encoding="utf-8") as f:
                f.write(f"管理员权限: {'是' if is_admin else '否'}\n")
        except:
            with open(log_file, "a", encoding="utf-8") as f:
                f.write("无法检查管理员权限\n")

    except Exception as e:
        # 如果日志写入失败,尝试简单的异常处理
        self.last_error = str(e)
        pass

 


    try:
        with open("lock_screen_log.txt", "a", encoding="utf-8") as f:
            f.write(f"未捕获异常: {exc_type.__name__}: {str(exc_value)}\n")
            import traceback
            traceback.print_tb(exc_traceback, file=f)
            f.write("="*50 + "\n")
    except:
        pass  # 如果日志写入失败,忽略

# 设置全局异常处理
sys.excepthook = handle_exception

 

root = tk.Tk()
# 创建应用实例
app = LockScreenApp(root)
# 运行应用
root.mainloop()