I want the tray icon to change according to the value of p_out
. Specifically depending on its value, I want it to get a different color.
Here's the code
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()
I tried to 'reset' the pystray icon
on every loop but it didn't work. The icon only changes when I stop and rerun the script.
As correctly stated in the comments, providing code that cannot run, does not help the community members to assist you. Τhe code references variables named white
, red
, green
, yellow
and
orange
, but these variables have not been defined or assigned values.
Despite all this, the dynamic update of the tray icon is certainly something that can be useful to others. Therefore, below you may find your code with the necessary corrections applied.
import ping3
import pystray
import threading # Import the threading module for creating threads
from PIL import Image # Import the Image module from PIL for creating images
def update_icon():
while True:
ping_output = ping3.ping("google.com", unit="ms")
print(f'\n{ping_output:4.0f}', end='')
if ping_output == 0:
img = Image.new("RGB", (32, 32), (255, 255, 255)) # 32px32px, white
elif 0 < ping_output <= 50:
img = Image.new("RGB", (32, 32), (0, 255, 0)) # 32px32px, green
elif 50 < ping_output <= 60:
img = Image.new("RGB", (32, 32), (255, 255, 0)) # 32px32px, yellow
elif 60 < ping_output < 100:
img = Image.new("RGB", (32, 32), (255, 165, 0)) # 32px32px, orange
elif ping_output >= 100:
img = Image.new("RGB", (32, 32), (255, 0, 0)) # 32px32px, red
icon.icon = img
if __name__ == "__main__":
icon = pystray.Icon("ping")
icon.icon = Image.new("RGB", (32, 32), (255, 255, 255)) # 32px32px, white
# Create a new thread to run the update_icon() function
thread = threading.Thread(target=update_icon)
# Start the thread
thread.start()
icon.run()
pip install pillow
.