1

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)

Rabe
  • 67
  • 1
  • 2
  • 7
  • `pystray.Icon.run()` is blocking (per the docs) but takes a callback parameter where your code can run. https://pystray.readthedocs.io/en/latest/reference.html – JonSG May 23 '21 at 19:20
  • @JonSG I tried adding setup too, `def setup(icon): icon.visible = True` & `icon.run(setup)` but then also its not executing – Rabe May 23 '21 at 19:36

1 Answers1

1

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)
JonSG
  • 10,542
  • 2
  • 25
  • 36