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但它不起作用。仅当我停止并重新运行脚本时,图标才会发生变化。
正如评论中正确指出的那样,提供无法运行的代码并不能帮助社区成员为您提供帮助。white\xce\xa4he 代码引用名为、red、green和yellow\n的变量orange,但这些变量尚未定义或赋值。
尽管如此,托盘图标的动态更新无疑对其他人有用。因此,您可以在下面找到应用了必要更正的代码。
\nimport 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()\nRun Code Online (Sandbox Code Playgroud)\npip install pillow。