3

Is there an option to create keyboard shortcut Ex.- Ctrl+Q to exit the application / close the window of a desktop application written in Kivy and Python? I am on Windows OS.

Thank you in advance.

  • Arnab
Arnab Majumder
  • 131
  • 1
  • 5

1 Answers1

6

Kivy's Window.on_keyboard (doc) event allows you to catch keyboard key pressing event.

Example app that exits if press ctrl+q:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window


class RootWidget(BoxLayout):
    pass


class TestApp(App):
    def build(self):
        Window.bind(on_keyboard=self.on_keyboard)  # bind our handler
        return RootWidget()

    def on_keyboard(self, window, key, scancode, codepoint, modifier):
        if modifier == ['ctrl'] and codepoint == 'q':
            self.stop()


if __name__ == '__main__':
    TestApp().run()
Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159
  • If you update the code. "if modifier == ['ctrl'] and codepoint == 'q':" to "if 'ctrl' in modifier and codepoint == 'q':" It will work as modifier is a list of strings. – Valthalin Jun 11 '22 at 08:30
  • @Valthalin fair point, thanks. I guess, it means that the condition will also work for ctrl+shift+Q what may not be what's expected. – Mikhail Gerasimov Jun 11 '22 at 13:09
  • Still new to kivy, but If you filtered the list of any constant modifiers, like mine had 'numlock', 'caplock in the list. Then it would be find to ask if "modifier == ['ctrl']". Instead of having to specify each cross over case. shift, alt, etc. – Valthalin Jun 12 '22 at 07:12