Search code examples
pythonmenugtkgobject

How to add keyboard navigation to a menu?


How can I add keyboard navigation (using Alt with underlines to suggest what other keys to use) to a python gtk gobject-introspection application.

This code works for showing a simple menu but does not add keyboard navigation:

mb = Gtk.MenuBar()
filemenu = Gtk.Menu()
filem = Gtk.MenuItem()
filem.set_label("File")
filem.set_submenu(filemenu)    
closem = Gtk.MenuItem()
closem.show()
closem.set_label("Close")
closem.connect("activate", Gtk.main_quit)
filemenu.append(closem)
mb.append(filem)

How can I change it to allow keyboard navigation?


Solution

  • Set the use-underline property and prepend _ to the key you want to use as shortcut.

    close_menu = Gtk.MenuItem()
    close_menu.set_label("_Close")
    close_menu.set_use_underline(True)
    

    If your version of PyGObject is recent enough, you can also use

    close_menu = Gtk.MenuItem("_Close", True)