pythongtkkeyboard-shortcutsgtk3gobject-introspection

Key binding for window/app in python Gtk+ 3 without menu items, UI manager, etc


I'm trying to use GTK3 and Cairo from Python for a minimal plotting application where the on-screen display of Cairo's output is for user convenience.

The typical usage is that I run a command, a plot pops up on screen and is also written to file, and I want to be able to dismiss the window as quickly as possible, ideally just a "q" keypress but also the common Ctrl-W and Ctrl-Q in addition to the default Alt-F4 (does anyone really use that regularly?!?).

I also want as little UI clutter in the window as possible: ideally just the standard window surround, no menus, toolbars, etc.

So... how can I bind my "q", "Ctrl-Q", etc. keybindings to Gtk.main_quit without having to a) create a cluttersome drop-down menu bar and b) go though the heavyweight Gtk.UIManager focused on by the Python Gtk+ 3 documentation here: http://python-gtk-3-tutorial.readthedocs.org/en/latest/menus.html . I hope this is possible, and doesn't require a lot of code (at least not as much as to set up all the menus!), but I can't find an example anywhere online: maybe I'm just searching for the wrong terms, being a GTK newbie.

Unfortunately there doesn't seem to be any documentation on making such a minimal accelerator setup, and the code to configure accelerator keys seems to differ a great deal between GTK2 and 3... thanks for helping.


Solution

  • Connect a signal to your main frame Win.connect('key-press-event', self.on_key_function) and in on_key_function (self, widget, event) check the value of event.keyval. For ESC is 65307 if you like hardcoded. Also, for key combinations, event.state report shift, alt(meta), and so on: if Gdk.ModifierType.CONTROL_MASK & event.state:do_something if ctrl is pressed You could have separate stataments for left-ctrl, right-alt; be sure not to try to capture predefined key combinations, thay may be consumed by window manager. A IDE with a good introspection will help you a lot, just write Gdk (previously imported) and autocompletion will popup a lot of functions/clases, most of them with a self-explanatory name.