0

I want it so that a function is performed when a key is pressed in kivy. I would like to have a simple example of how to do this as I want to implement it in my app. Would appreciate any help.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Fat Trat
  • 65
  • 1
  • 10
  • You can use [`WindowBase.RequestKeyboard`](https://kivy.org/doc/stable/api-kivy.core.window.html) and set a keyboard listener on your widget that will read the keycode and perform some function. – Alias Cartellano Jul 08 '22 at 17:14

1 Answers1

1

First import the Window class:

from kivy.core.window import Window

You can create a function that handles keyboard events:

class HiWorld(Widget):

    def __init__(self, **kwargs):
        super(HiWorld, self).__init__(**kwargs)
        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down=self._on_keyboard_down)

    def _keyboard_closed(self):
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard = None

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if keycode[1] == 'e': #for example if you hit the key "e"
            self.do_something_e()
        elif keycode[1] == 'x': #if x is pressed
            self.do_something_x()
        return True
    def do_something_e(self):
        print("You pressed e")
    def do_something_x(self):
        print("You pressed x")
        

Or you can you use the official example form kivy documentation:

import kivy
kivy.require('1.0.8')

from kivy.core.window import Window
from kivy.uix.widget import Widget


class MyKeyboardListener(Widget):

    def __init__(self, **kwargs):
        super(MyKeyboardListener, self).__init__(**kwargs)
        self._keyboard = Window.request_keyboard(
            self._keyboard_closed, self, 'text')
        if self._keyboard.widget:
            # If it exists, this widget is a VKeyboard object which you can use
            # to change the keyboard layout.
            pass
        self._keyboard.bind(on_key_down=self._on_keyboard_down)

    def _keyboard_closed(self):
        print('My keyboard have been closed!')
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard = None

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        print('The key', keycode, 'have been pressed')
        print(' - text is %r' % text)
        print(' - modifiers are %r' % modifiers)

        # Keycode is composed of an integer + a string
        # If we hit escape, release the keyboard
        if keycode[1] == 'escape':
            keyboard.release()

        # Return True to accept the key. Otherwise, it will be used by
        # the system.
        return True


if __name__ == '__main__':
    from kivy.base import runTouchApp
    runTouchApp(MyKeyboardListener())
DXNI
  • 149
  • 14