0

I found that code on the Internet :

#!/usr/bin/env python3

from gi.repository import Gtk

def popup_menu(icon, button, time):

    menu = Gtk.Menu()

    menuitemAbout = Gtk.MenuItem(label="About")
    menu.append(menuitemAbout)
    menuitemQuit = Gtk.MenuItem(label="Quit")
    menu.append(menuitemQuit)
    menu.show_all()

    menu.popup(None, None, None, None, button, time)

statusicon = Gtk.StatusIcon()
statusicon.set_from_stock(Gtk.STOCK_HOME)
statusicon.set_title("StatusIcon")
statusicon.connect("popup-menu", popup_menu)

window = Gtk.Window()
window.connect("destroy", lambda q: Gtk.main_quit())
window.show_all()

Gtk.main()

A small menu should appear when I right-click on the status icon, but when I run the code and click, the menu appears and immediately disappears.

Any idea why ?

arthropode
  • 1,361
  • 2
  • 12
  • 19

1 Answers1

3

Finally, I found a solution : the variable menu is destroyed when I leave the function. So I have to save it. Thus I transformed my code into a class and menu is saved in a attribute :

#!/usr/bin/env python3

from gi.repository import Gtk

class Menu:
    def __init__(self):
        statusicon = Gtk.StatusIcon()
        statusicon.set_from_stock(Gtk.STOCK_HOME)
        statusicon.set_title("StatusIcon")
        statusicon.connect("popup-menu", self.popup_menu)

        window = Gtk.Window()
        window.connect("destroy", lambda q: Gtk.main_quit())
        window.show_all()

        Gtk.main()

    def popup_menu(self, icon, button, time):
        print(time, button)

        self.menu = Gtk.Menu()

        menuitemAbout = Gtk.MenuItem(label="About")
        self.menu.append(menuitemAbout)
        menuitemQuit = Gtk.MenuItem(label="Quit")
        self.menu.append(menuitemQuit)
        self.menu.show_all()

        self.menu.popup(None, None, None, None, button, time)

Menu()
arthropode
  • 1,361
  • 2
  • 12
  • 19