kivy
  1. kivy-user-input-and-touch-events

User Input and Touch Events - Kivy Events and Interactions

Kivy is an open-source framework for developing multi-touch mobile applications that are capable of running on various platforms such as Windows, macOS, Linux, etc. In this tutorial, we will learn about user input and touch events in Kivy.

Syntax

def on_touch_down(self, touch):
    # Event handler - touch down event
    pass

def on_touch_move(self, touch):
    # Event handler - touch move event
    pass

def on_touch_up(self, touch):
    # Event handler - touch up event
    pass
  • on_touch_down() function is called when a touch down event is detected.
  • on_touch_move() function is called when the touch is moved.
  • on_touch_up() function is called when the touch is lifted.

Example

from kivy.app import App
from kivy.uix.button import Button

class MyButton(Button):
    def on_touch_down(self, touch):
        # Change button color on touch down
        self.background_color = (0.3, 0.3, 0.3, 1)
        return super(MyButton, self).on_touch_down(touch)

    def on_touch_up(self, touch):
        # Change button color back to default on touch up
        self.background_color = (0.1, 0.5, 1, 1)
        return super(MyButton, self).on_touch_up(touch)

class MyTouchApp(App):
    def build(self):
        return MyButton(text='Touch me!', font_size=50)

if __name__ == '__main__':
    MyTouchApp().run()

Output

Upon running the above example, we get a button that changes color on touch down and changes back to its original color on touch up.

Explanation

In the above example, we first import the Button class and the App class from the kivy.uix.button and kivy.app modules, respectively. We then define our MyButton class that inherits from the Button class and defines two event handler functions, on_touch_down() and on_touch_up(). We also define our MyTouchApp class that inherits from the App class and returns an instance of our MyButton class with some text and font size.

In our on_touch_down() function, we change the background color of our button, and in our on_touch_up() function, we change it back to its original color. We then call the on_touch_down() and on_touch_up() functions of the parent class using the super() function, which ensures that the default touch event behavior is still executed.

Use

  • User input events
  • Touch events
  • Gesture recognition

Important Points

  • on_touch_down(), on_touch_move(), and on_touch_up() functions are used for detecting touch events.
  • Kivy supports multi-touch events.
  • You can customize the default touch event behavior by defining your event handlers.

Summary

In this tutorial, we learned about user input and touch events in Kivy. We also saw a simple example of how to customize the button's color using touch events.

Published on: