0

I'm trying to build an application using python pystray module and I've tested my code in all Windows10, Ubuntu20 and MacOS11 machines. In Ubuntu the behavior is little different. In Windows and MacOS, when I click the "Exit" menu item, the system tray icon disappears right away and when both threads finished the program exits. But in Ubuntu when I click the "Exit" menu item, the icon does not dissappear. It is visible until both threads exit.

import pystray
from PIL import ImageDraw, ImageFont, Image
import time


FONT = ImageFont.truetype("UbuntuMono-R.ttf", 50)
# FONT = ImageFont.truetype("tahoma.ttf", 50) # Windows
# FONT = ImageFont.truetype("Symbol.ttf", 50) # MacOS


def get_empty_image():
    return Image.new('RGBA', (100, 50))  # Empty image


def refresh(icon):
    image = get_empty_image()
    draw = ImageDraw.Draw(image)
    draw.text((0, 0), ":-)", font=FONT, fill='white')
    icon.icon = image
    icon.title = "Title"


def update_forever(icon):
    icon.visible = True
    while icon.visible:
        # DO SOME WORK HERE
        refresh(icon)
        time.sleep(10)


def exit_method(icon):
    icon.visible = False
    icon.stop()


menu = (pystray.MenuItem('Exit', exit_method),)
icon = pystray.Icon("icon_name", get_empty_image(), "Starting...", menu)
icon.run(update_forever)

As a workaround, I can use a smaller sleep time and hide/exit the icon faster but is there a better option? I'm using appindicator module here and gtk, xorg modules don't even show the icon.

Question is: Is it possible to hide the tray icon right away in Ubuntu and if so how?

4

0 回答 0