Search code examples
pythonmenucontextmenupygtk

Submenu item does not call function [with working solution]


    #submenu
    clearMenu = gtk.Menu()

    item = gtk.MenuItem("submenu item")
    item.connect("activate", lambda w: self.callBackFunction())
    clearMenu.append(item)
    item.show()


    '''TOP level'''
    menu = gtk.Menu()

    item = gtk.ImageMenuItem("Item1")
    img = gtk.Image()
    img.set_from_file('image1.png')
    item.set_image(img)
    menu.append(item)
    item.set_submenu(clearMenu) #attach submenu
    item.show()

    item = gtk.ImageMenuItem("Item2")
    img = gtk.Image()
    img.set_from_file('image2.png')
    item.set_image(img)   
    item.connect("activate", lambda w: self.callBackFunction())
    menu.append(item)
    item.show()

My top level item "Item2" calls defined function "callBackFunction". But why "submenu item" does not? What i'm doing wrong?


EDIT

here is how i've managed to force submenu items kick-in desired action:

item.connect("button-press-event", self.callBackFunction, argument1, argument2)

But i still dont get it why event "activate" does not works on submenu items, while works in top level menu items


Solution

  • It's an inherent problem with submenu focus explained here:

    the submenu doesn't get focus until the menu item it's attached to is clicked (even though the submenu appears when the mouse is over the menu item.)

    The upshot is that items in the sub menu don't emit the activate signal unless the parent menu item is clicked first.

    This explains why keyboard navigation seems to work.

    I've been working around this problem for more than a year, and I don't know of any solution to it — just the "button-press-event" workaround you've discovered.