Aleksander Alekseev
Aleksander Alekseev

Reputation: 1894

Python 3 & GTK3: crossplatform tray icon

It's possible to create a tray icon with a menu using AppIndicator3. But this solution is not portable. For instance it doesn't work on FreeBSD since there is no libappindicator3 on this system. I suspect that such code doesn't work on Windows and MacOS either.

How to do the same without AppIndicator3 so code would work on all (or almost all) systems?

Upvotes: 7

Views: 2808

Answers (1)

Aleksander Alekseev
Aleksander Alekseev

Reputation: 1894

Ok, I think I figured it out. The idea is to fallback to Gtk.StatusIcon if AppIndicator3 is unavailable:

class TrayIcon:

    def __init__(self, appid, icon, menu):
        self.menu = menu

        APPIND_SUPPORT = 1
        try:
            from gi.repository import AppIndicator3
        except:
            APPIND_SUPPORT = 0

        if APPIND_SUPPORT == 1:
            self.ind = AppIndicator3.Indicator.new(
                appid, icon, AppIndicator3.IndicatorCategory.APPLICATION_STATUS)
            self.ind.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
            self.ind.set_menu(self.menu)
        else:
            self.ind = Gtk.StatusIcon()
            self.ind.set_from_file(icon)
            self.ind.connect('popup-menu', self.onPopupMenu)

    def onPopupMenu(self, icon, button, time):
        self.menu.popup(None, None, Gtk.StatusIcon.position_menu, icon, button, time)

Works on Linux + Unity, Linux + Xfce, FreeBSD + i3.

See also:

Upvotes: 7

Related Questions