Kivy provides extensive support for touch and gestures, enabling the creation of highly interactive applications. This includes detecting single touches, multitouch gestures, and custom gestures. Here's a detailed look at how to handle touch and gestures in Kivy.
Kivy supports various touch events that can be handled within widgets. The primary touch events are:
on_touch_down Called when a touch event begins.
on_touch_move Called when a touch event moves.
on_touch_up Called when a touch event ends.
Basic Touch Handling :To handle touch events, you need to override these methods in your widget class.
from kivy.app import App
from kivy.uix.widget import Widget
class TouchWidget(Widget):
def on_touch_down(self, touch):
print('Touch down at', touch.pos)
return super(TouchWidget, self).on_touch_down(touch)
def on_touch_move(self, touch):
print('Touch move at', touch.pos)
return super(TouchWidget, self).on_touch_move(touch)
def on_touch_up(self, touch):
print('Touch up at', touch.pos)
return super(TouchWidget, self).on_touch_up(touch)
class TouchApp(App):
def build(self):
return TouchWidget()
if __name__ == '__main__':
TouchApp().run()
on_touch_down, on_touch_move, and on_touch_up methods print the touch position whenever a touch event occurs.
Kivy includes a Gesture library for recognizing multitouch gestures. This allows you to define custom gestures and recognize them in your application.
First, import the necessary modules:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.gesture import Gesture, GestureDatabase
Define a widget that can recognize gestures:
class GestureWidget(Widget):
def __init__(self, **kwargs):
super(GestureWidget, self).__init__(**kwargs)
self.gdb = GestureDatabase()
# Define a simple circular gesture
gesture_str = "eNp1TUEKwDAIBNFg/y1En4l/loXCqEiMSa..."
self.gesture = Gesture.fromstr(gesture_str)
self.gdb.add_gesture(self.gesture)
def on_touch_down(self, touch):
touch.ud['gesture'] = self.gdb.gesture()
return super(GestureWidget, self).on_touch_down(touch)
def on_touch_move(self, touch):
gesture = touch.ud['gesture']
gesture.add_point(*touch.pos)
return super(GestureWidget, self).on_touch_move(touch)
def on_touch_up(self, touch):
gesture = touch.ud['gesture']
gesture.add_point(*touch.pos)
match = self.gdb.find(gesture, minscore=0.70)
if match:
print('Gesture recognized:', match)
else:
print('No matching gesture found')
return super(GestureWidget, self).on_touch_up(touch)
class GestureApp(App):
def build(self):
return GestureWidget()
if __name__ == '__main__':
GestureApp().run()
In this example: