Search code examples
python-3.xpygtkpygobject

Detect combination of keys pressed in PyGtk3 Python3


I want to detect when CTRL + Q are pressed and then perform an action. Now, I have code to detect if one key is pressed, but not a combination.

Actually, my function is:

def on_key_press_event(self, widget, event):
    keyname = Gdk.keyval_name(event.keyval)
    print("Key %s (%d) pulsada" % (keyname, event.keyval))
    if keyname ==  "q":
        print (event.state)
        if event.state == "CONTROL_MASK":
            print ("controlcu")
    if keyname == "Escape":
        self.entrada.set_text("")
    if keyname == "Return":
        self.button1.clicked()
        self.entrada.set_text("")

As you can see I tried with the "if keyname == 'Escape'" thing. I can find only things for PyGtk2 but no PyGtk3. Thanks for your help!

+info: Some things are in spanish: pulsada = pressed; controlcu = controlQ; entrada = entry.


Solution

  • Don't compare names use the actual keyval/modifier. Some docs: https://lazka.github.io/pgi-docs/#Gtk-3.0/classes/Widget.html#Gtk.Widget.do_key_press_event

    Then here are the Gdk.KEY_* constants for event.keyval: https://lazka.github.io/pgi-docs/#Gdk-3.0/constants.html#details

    And the modifiers for event.state: https://lazka.github.io/pgi-docs/#Gdk-3.0/flags.html#Gdk.ModifierType

    (FYI it is not called pygtk3)