使用 pystray 动态更改托盘图标

Dou*_*lva 5 python taskbar pystray

我希望托盘图标根据 的值进行更改p_out。具体取决于它的值,我希望它有不同的颜色。

这是代码

import pystray
import ping3

while True:
    p_out = ping3.ping("google.com", unit="ms")
    if p_out == 0:
        img = white
    elif p_out >= 999:
        img = red
    else:
        print(f'\n{p_out:4.0f}', end='')
        if p_out <= 50:
            img = green
        elif p_out <= 60:
            img = yellow
        elif p_out < 100:
            img = orange
        elif p_out >= 100:
            img = red

    icon = pystray.Icon(" ", img)
    icon.run()
Run Code Online (Sandbox Code Playgroud)

我尝试在每个循环上“重置”pystray,icon但它不起作用。仅当我停止并重新运行脚本时,图标才会发生变化。

And*_*ris 9

正如评论中正确指出的那样,提供无法运行的代码并不能帮助社区成员为您提供帮助。white\xce\xa4he 代码引用名为、redgreenyellow\n的变量orange,但这些变量尚未定义或赋值。

\n

尽管如此,托盘图标的动态更新无疑对其他人有用。因此,您可以在下面找到应用了必要更正的代码。

\n
import ping3\nimport pystray\nimport threading  # Import the threading module for creating threads\nfrom PIL import Image  # Import the Image module from PIL for creating images\n\n\ndef update_icon():\n    while True:\n        ping_output = ping3.ping("google.com", unit="ms")\n        print(f\'\\n{ping_output:4.0f}\', end=\'\')\n        if ping_output == 0:\n            img = Image.new("RGB", (32, 32), (255, 255, 255))  # 32px32px, white\n        elif 0 < ping_output <= 50:\n            img = Image.new("RGB", (32, 32), (0, 255, 0))  # 32px32px, green\n        elif 50 < ping_output <= 60:\n            img = Image.new("RGB", (32, 32), (255, 255, 0))  # 32px32px, yellow\n        elif 60 < ping_output < 100:\n            img = Image.new("RGB", (32, 32), (255, 165, 0))  # 32px32px, orange\n        elif ping_output >= 100:\n            img = Image.new("RGB", (32, 32), (255, 0, 0))  # 32px32px, red\n        icon.icon = img\n\n\nif __name__ == "__main__":\n    icon = pystray.Icon("ping")\n    icon.icon = Image.new("RGB", (32, 32), (255, 255, 255))  # 32px32px, white\n    # Create a new thread to run the update_icon() function\n    thread = threading.Thread(target=update_icon)\n    # Start the thread\n    thread.start()\n    icon.run()\n
Run Code Online (Sandbox Code Playgroud)\n

笔记:

\n
    \n
  • 为了使用Image 模块,您必须首先使用pip等包管理器安装Pillow,使用如下命令:pip install pillow
  • \n
  • 创建新线程的目的——运行update_icon是让托盘图标在后台继续更新,而不阻塞主线程的执行。
  • \n
  • 虽然32x32 像素是图标的常见尺寸,但它不一定是唯一可以使用的尺寸。
  • \n
  • 使用一段时间 True循环运行连续任务会消耗大量系统资源,例如 CPU 和内存,这会影响程序的整体性能。但是,我不会对此提出任何建议,因为它与当前问题无关。
  • \n
\n