You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下Python亮度调节应用二次最小化报错OSError: [WinError 6]

问题原因

你遇到的WinError 6无效句柄错误,核心原因是:第一次最小化后,点击托盘菜单的「Open GUI」调用了icon.stop(),这会销毁pystray内部的窗口句柄。第二次再点击最小化按钮调用self.icon.run()时,这个Icon实例已经失效,无法重新创建窗口,因此抛出错误。

解决方案

以下两种方案都能解决问题,按需选择:

方案1:每次最小化时重新创建托盘Icon实例

直接在最小化方法里重新初始化托盘图标,避免复用已失效的实例:

def minimize_app(self):
    self.root.withdraw()
    # 每次最小化都重新生成托盘图标实例
    self.icon = pystray.Icon('icon', img, menu=pystray.Menu(
        pystray.MenuItem("Open GUI", self.on_move_clicked),
        pystray.MenuItem("Exit", self.on_move_clicked)
    ))
    self.icon.run()

方案2:用状态变量控制托盘运行状态

新增一个状态变量,跟踪托盘是否正在运行,避免重复调用icon.run():

class DesktopBrightnessApp:
     def __init__(self):
            # (补充self.root的初始化代码,比如self.root = tb.Window())
            self.minimize_button = tb.Button(self.root, text="Minimize", 
               command=self.minimize_app)
            self.minimize_button.place(x=215, y=200)

            self.icon = pystray.Icon('icon', img, menu=pystray.Menu(
                pystray.MenuItem("Open GUI", self.on_move_clicked),
                pystray.MenuItem("Exit", self.on_move_clicked)
                ))
            self.tray_is_running = False  # 新增状态变量

     def on_move_clicked(self, icon, item):
            if str(item) == "Open GUI":
               icon.stop()
               self.tray_is_running = False  # 更新状态
               self.root.deiconify()

            elif str(item) == "Exit":
               icon.stop()
               self.tray_is_running = False
               self.root.destroy()

     def minimize_app(self):
            self.root.withdraw()
            if not self.tray_is_running:  # 仅当托盘未运行时启动
                self.tray_is_running = True
                self.icon.run()

内容的提问来源于stack exchange,提问作者Zephyrus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 00:42:26