Search code examples
pythonpython-3.xpystray

pystray with other codes execution


I require a code, to launch tray icon and execute other parts of codes...

So for that I tried below:

from pystray import MenuItem as item
import pystray
from PIL import Image, ImageDraw
import time

def action():
    pass

def exit(icon):
    icon.stop()

image = Image.open("image.PNG")
menu = (item('name', action), item('Exit', exit))
icon = pystray.Icon("A", image, "B", menu)
i = 0
icon.run()
while i != 50:
    print('test')
    time.sleep(1)
    i += 1

This launches the tray icon, but doesn't execute my loop. (it only executes post I stop the Icon)


Solution

  • Per the documentation (https://pystray.readthedocs.io/en/latest/reference.html) , pystray.Icon.run() is blocking until stop(). You can pass it a callback though that will be run on a separate thread.

    def foo(icon):
        icon.visible = True
        i = 0
        while i <= 5:
            print('test')
            time.sleep(1)
            i += 1
        print('now blocking until stop()...')
    
    image = Image.open("image.PNG")
    menu = (item('name', action), item('Exit', exit))
    icon = pystray.Icon("A", image, "B", menu)
    icon.run(foo)