Search code examples
pythonwindowspystray

How to create menu and update icon in Pystray


I want to use pystray module in Python to create a system tray app on Windows.

Code

Until now I managed to write this:

import pystray
from PIL import Image

image = Image.open("image.gif")
icon = pystray.Icon(name ="SPAM!", icon =image, title ="MOBASuite", menu =None)
icon.run()

Problem

I had a hard time to find out how this works. Its not clearly explained in a documentation.

When I run the this program, 3 icons are created and I must hover mouse over them to become one icon. Same thing when I close the program.

Questions

  1. How can I create a menu after right-clicking on the icon?
  2. How can I add items to the menu and set default one? (The default-item should be called if I left-click on the icon).
  3. How can I update the icon?

Solution

  • from pystray import MenuItem as item
    import pystray
    from PIL import Image
    
    def action():
        pass
    
    image = Image.open("image.jpg")
    menu = (item('name', action), item('name', action))
    icon = pystray.Icon("name", image, "title", menu)
    icon.run()
    

    This work for me

    I recomend use lambda to call a method

    item('Call something', lambda :  method())