Touch Input/Mouse Input
Subscribe to Tech with Tim
This kivy tutorial will show you how to get both touch and mouse input from the user.
Importing Modules
Like usual, before we start we need to import a few things from Kivy.
from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import ObjectProperty
Setting up the GUI
For this program we will have a very simply GUI that consists of one Button. We will place this button inside of the Touch class which we will create in the next step. We will also add an ID and global variable for our button so we can reference it later in our python script.
<Touch>: btn: btn Button: id = btn text:"My Btn"
Touch Class
To handle input from the user will will create a new class called Touch. This class will inherit from Widget and be responsible for holding our widgets and GUI elements and for handling input from the user.
Inside this touch class we will override 3 methods from the Widget class that do the following.
on_touch_down: Is triggered when the user first presses on the screen.
on_touch_up: Is triggered when the user releases the mouse or moves their finger off the screen.
on_touch_move: Is triggered when the user is touching the screen and moving their finger or mouse.
class Touch(Widget): btn = ObjectProperty(None) def on_touch_down(self, touch): print("Mouse Down", touch) def on_touch_move(self, touch): print("Mouse Move", touch) def on_touch_up(self, touch): print("Mouse UP", touch)
Now if we run our program we will see that our input is recorded and printed to the screen.
Potential Problems
You may have noticed that when we try to click the button nothing happens! This is because we have overrode the functions that usually handle this action. To give some kind of feedback to the user when they press the button we can do the following.
class Touch(Widget): btn = ObjectProperty(None) def on_touch_down(self, touch): print("Mouse Down", touch) self.btn.opacity = 0.5 def on_touch_move(self, touch): print("Mouse Move", touch) def on_touch_up(self, touch): print("Mouse UP", touch) self.btn.opacity = 1
Full Code
import kivy from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import ObjectProperty class Touch(Widget): btn = ObjectProperty(None) def on_touch_down(self, touch): print("Mouse Down", touch) self.btn.opacity = 0.5 def on_touch_move(self, touch): print("Mouse Move", touch) def on_touch_up(self, touch): print("Mouse UP", touch) self.btn.opacity = 1 class MyApp(App): def build(self): return Touch() if __name__ == "__main__": MyApp().run()
<Touch>: btn: btn Button: id: btn text:"My Btn"