Search code examples
pythongtkgobject

Python Gtk3 right click menu


I am trying to create a pop-up menu in python/gtk3. So far I have tried the following code:

from gi.repository import Gtk
def show_menu(self, *args):     
    menu = Gtk.Menu()
    i1 = Gtk.MenuItem("Item 1")
    menu.append(i1)
    i2 = Gtk.MenuItem("Item 2")
    menu.append(i2)
    i2.show()    
    i1.show()
    menu.popup(None, None, None, None, 0, Gtk.get_current_event_time())
    print("Done")


window = Gtk.Window() 
button = Gtk.Button("Create pop-up") 
button.connect("clicked", show_menu) 
window.add(button) 
window.show_all()
Gtk.main()

but the popup menu doesn't show up? What am I doing wrong?


Solution

  • Since menu is a local variable in the show_menu() function, and it is not referenced by anything else, its reference count drops to 0 and it gets destroyed at the end of the function; unfortunately, that is right when you are expecting to see it.

    Instead, create menu in the global scope which makes it so that menu isn't local to one function anymore, and so it won't get destroyed at the end of the function.

    from gi.repository import Gtk
    
    def show_menu(self, *args):
        i1 = Gtk.MenuItem("Item 1")
        menu.append(i1)
        i2 = Gtk.MenuItem("Item 2")
        menu.append(i2)
        menu.show_all()
        menu.popup(None, None, None, None, 0, Gtk.get_current_event_time())
        print("Done")
    
    window = Gtk.Window()
    button = Gtk.Button("Create pop-up")
    menu = Gtk.Menu()
    button.connect("clicked", show_menu)
    window.connect('destroy', Gtk.main_quit)
    window.add(button)
    window.show_all()
    Gtk.main()