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()
NOTES:
- In order to use the Image module, you must first install Pillow, with a package manager like pip, using a command like this:
pip install pillow
.
- The purpose of creating a new thread -to run update_icon function- is to allow the tray icon to continue updating in the background, without blocking the main thread of execution.
- While 32x32px is a common size for icons, it is not necessarily the only size that can be used.
- Using a while True loop to run a continuous task can consume a large amount of system resources, such as CPU and memory, which can impact the overall performance of your program. However, I will not suggest anything about it as it is not relevant to the present question.