Ubuntu – How to create and use keyboard shortcuts in a Gtk app that I am developing

application-developmentgtkpythonshortcut-keys

I am creating an application for the Ubuntu App Showdown in Python + Gtk with quickly. I am calling it Discvur. I would have liked to include some keyboard shortcuts.

Searching the web, I found this page about AccelGroup and this page about gtk_widget_add_accelerator but I don't understand how to start with it. Could you tell me how I would define an appropriate signal and then use it in my application?

Best Answer

Here's some bits of code from one of my Python + Gtk apps, further extended according to the comments to this answer:

self.my_accelerators = Gtk.AccelGroup()
self.entry = Gtk.builder.get_object("entry1")
self.add_accelerator(self.entry, "<Control>b", signal="backspace")
...

def add_accelerator(self, widget, accelerator, signal="activate"):
    """Adds a keyboard shortcut"""
    if accelerator is not None:
        #if DEBUG:
            #print accelerator, widget.get_tooltip_text()
        key, mod = Gtk.accelerator_parse(accelerator)
        widget.add_accelerator(signal, self.my_accelerators, key, mod, Gtk.AccelFlags.VISIBLE)