Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 811
Aleksander Alekseev Avatar asked Jun 21 '16 06:06

Aleksander Alekseev


People also ask

What is the Python 3?

What is Python 3? Python 3 is a newer version of the Python programming language which was released in December 2008. This version was mainly released to fix problems that exist in Python 2. The nature of these changes is such that Python 3 was incompatible with Python 2. It is backward incompatible.

How do I install Python 3?

Python 3 can be installed using the official Python 3 installer. Go to the Python Releases for Mac OS X page and download the latest stable release macOS 64-bit/32-bit installer. After the download is complete, run the installer and click through the setup steps leaving all the pre-selected installation defaults.

Is Python 3 a language?

Python is a high-level, interpreted, general-purpose programming language.

What version is python3?

Python 3.0 was released on December 3rd, 2008. It was designed to rectify certain flaws in the earlier version. This version is not completely backward-compatible with previous versions. However, many of its major features have since been back-ported to the Python 2.6. x and 2.7.


1 Answers

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:

  • http://ubuntuforums.org/showthread.php?t=1923373#post11902222
  • https://github.com/syncthing/syncthing-gtk/blob/master/syncthing_gtk/statusicon.py
  • https://github.com/afiskon/py-gtk-example
like image 64
Aleksander Alekseev Avatar answered Sep 23 '22 03:09

Aleksander Alekseev