Reputation: 540
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?
Upvotes: 1
Views: 3068
Reputation: 339
In the callback, do menu.attach_to_widget (widget, None)
. Instead of *args it may be simpler to just supply the right arguments to the callback as well, which I believe in this case would just be be `show_menu(self, widget, user_data)'.
The attach_to_widget basically passes responsibility for the menu to the GtkWindow, including all cleanup, positioning, etc..
Upvotes: 1
Reputation: 57920
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()
Upvotes: 5