Search code examples
pythongtk

Get Parent of Gtk Submenu


Calling get_parent() on a Gtk submenu (item) does not yield its parent menu but rather the object it extends from. Is it possible to identify the parent menu?

I need it for a much more complex menu structure than the one below MCVE, in order to toggle the RadioMenuItem checkboxes of the above-lying menuitems.

menu = Gtk.Menu()
menu_item = Gtk.MenuItem('blah', 'blah')
menu_item.set_submenu(create_submenu())
menu.append(menu_item)

def create_submenu():
   submenu = Gtk.Menu()
   submenu_item = Gtk.MenuItem('blah', 'blah')
   submenu.connect('activate', do_something)
   submenu.append(submenu_item)
   return submenu

def do_something(widget):
   widget.get_parent().set_label('this is not the parent menu') # <--- refers to Gtk.Window, not our menu above

Solution

  • As mentioned in the comments by Edouard Thiel, you can indeed run submenu.get_parent().get_attach_widget() to receive a reference to the parent menu. More info at https://people.debian.org/~osamu/gtk3tutor/python-gtk3/Gtk.Menu.get_attach_widget.page