• No results found

Kivy Cookbook - Sample Chapter

N/A
N/A
Protected

Academic year: 2021

Share "Kivy Cookbook - Sample Chapter"

Copied!
33
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

The author biography

The author biography

A preview chapter from the book, Chapter

A preview chapter from the book, Chapter 2

2 'Input, Motion, and Touch'

'Input, Motion, and Touch'

A synopsis of the

A synopsis of the book’s content

book’s content

(3)

About the Author 

About the Author 

Hugo Solis

Hugo Solis

 is an assistant professor in the physics department at the  is an assistant professor in the physics department at the University of CostaUniversity of Costa Rica. In the same institution, he collaborates with CITIC and CICIMA.

Rica. In the same institution, he collaborates with CITIC and CICIMA. His current researchHis current research interests include computational cosmology

interests include computational cosmology, complexity, and the i, complexity, and the innflfluence of hydrogen onuence of hydrogen on material properties. He has

material properties. He has wide experience in languages, including C/C++ and wide experience in languages, including C/C++ and Python forPython for scienti

scientifific programming and visualization. He is c programming and visualization. He is a member of the a member of the Free Software FoundationFree Software Foundation and has contributed code to some free software projects. He has also been a

and has contributed code to some free software projects. He has also been a technicaltechnical reviewer for

reviewer for Mastering Object-oriented PythonMastering Object-oriented Python,, Kivy: Interactive Applications in PythonKivy: Interactive Applications in Python, and, and Learning Object-Oriented Programming

Learning Object-Oriented Programming by Packt Publishing. Currentlyby Packt Publishing. Currently, he is in , he is in charge of thecharge of the IFT, a Costa Rican scienti

IFT, a Costa Rican scientifific nonproc nonprofifit organization for the multidisciplinary practice of physicst organization for the multidisciplinary practice of physics ((

http://iftucr.org

http://iftucr.org

).).

(4)

Preface

Preface

The book is full of

The book is full of practical task-based recipes to be performed while developing multitopractical task-based recipes to be performed while developing multitouchuch applications with Kivy. The focus of this

applications with Kivy. The focus of this book is to guide book is to guide you through the Kivy framework toyou through the Kivy framework to develop apps and get your apps

develop apps and get your apps ready for distribution in App ready for distribution in App Stores and Android devices. We'llStores and Android devices. We'll focus on common, real-world scenarios. You'll be

focus on common, real-world scenarios. You'll be able to able to leverage these recipes right leverage these recipes right awayaway,, which allows you to create most diverse apps and learn how to distribute them using the Kivy which allows you to create most diverse apps and learn how to distribute them using the Kivy framework, and widen your pro

framework, and widen your profificiency in developing multitouch applications with ciency in developing multitouch applications with Kivy.Kivy.

What this book covers

What this book covers

Chapter 1

Chapter 1,, Kivy and the Kv LanguageKivy and the Kv Language, introduces the Python code, Kv , introduces the Python code, Kv language, widgets,language, widgets, and Kivy garden. The

and Kivy garden. The topics covered in this chapter lay the topics covered in this chapter lay the foundation for the remainingfoundation for the remaining code samples in each

code samples in each chapterchapter.. Chapter 2

Chapter 2,, Input, Motion, and TouchInput, Motion, and Touch, demonstrates some of the most , demonstrates some of the most common recipient-common recipient-related management tasks, such as

related management tasks, such as evolving to the touchscreen, using the gyroscope, andevolving to the touchscreen, using the gyroscope, and detecting multitapping. You

detecting multitapping. You'll also 'll also learn how to learn how to recognize touch shapes, record gestures,recognize touch shapes, record gestures, and differentiate between touch and motion events.

and differentiate between touch and motion events. Chapter 3

Chapter 3,, EventsEvents, shows how to schedule a one-time event and a repetitive event. Triggering, shows how to schedule a one-time event and a repetitive event. Triggering events, de

events, defifining widget events, creating custom events are also covered in this chapter.ning widget events, creating custom events are also covered in this chapter.

Chapter 4

Chapter 4,, WidgetsWidgets, covers the manipulation of widget , covers the manipulation of widget tree, traversing of tree. It also tree, traversing of tree. It also coverscovers the FloatLayout, BoxLayout, StackLayout, AnchorLayout, and action bar.

the FloatLayout, BoxLayout, StackLayout, AnchorLayout, and action bar. Chapter 5

Chapter 5,, Graphics – Canvas and Graphics – Canvas and InstructionsInstructions, explains various methods, such as, explains various methods, such as separating with the

separating with the screen managerscreen manager, using context instructions, and using drawing, using context instructions, and using drawing instructions. Yo

instructions. You'll learn u'll learn how to modify how to modify with multitouching and storing with multitouching and storing and retrievingand retrieving the coordinate space context.

the coordinate space context. Chapter 6

Chapter 6,, Advancing Graph Advancing Graphics – Shaders and Reics – Shaders and Rendering ndering , covers Carousel, l, covers Carousel, layouts,ayouts, and shaders. The

and shaders. The other topics covered in this chapter are rendering in other topics covered in this chapter are rendering in a Framebuffera Framebuffer and optimizing graphics.

(5)

Chapter 7

Chapter 7,, The API in DetailThe API in Detail, introduces API and covers the logging objects, parsing, applying, introduces API and covers the logging objects, parsing, applying utils, using spelling, adding effects, and add

utils, using spelling, adding effects, and adding text.ing text. Chapter 8

Chapter 8,, Packaging our Apps for PC Packaging our Apps for PC , shows how to per, shows how to perform packing for Windows, Linux,form packing for Windows, Linux, and MacOs. It also

and MacOs. It also shows multimedia for Windoshows multimedia for Windows and running apps in Windows and MacOS.ws and running apps in Windows and MacOS. Chapter 9

Chapter 9,, Kivy for Mobile DevicesKivy for Mobile Devices, explains various methods, such as packaging for iOS and, explains various methods, such as packaging for iOS and resizing the screen into iOS.

resizing the screen into iOS. YoYou'll learn preparing for the u'll learn preparing for the App Store, packaging for Android,App Store, packaging for Android, and resizing the

(6)

2

2

Input, Motion,

Input, Motion,

and Touch

and Touch

In this chapter, we will cover: In this chapter, we will cover:

 Using the mouseUsing the mouse 

 Evolving to the Evolving to the touchscreentouchscreen 

 Working with the accelerometerWorking with the accelerometer 

 Using the gyroscopeUsing the gyroscope 

 The DifThe Differences between the touch and motion ferences between the touch and motion eventeventss 

 Recognizing touch shapesRecognizing touch shapes 

 Detecting multitapping Detecting multitapping  

 Grabbing touch Grabbing touch eventsevents 

 RecordinRecording g gesturesgestures

Introduction

Introduction

The Kivy framework is able to handle most common types of input and actions such as The Kivy framework is able to handle most common types of input and actions such as mouse, touchscreen, accelerometer, and gyroscope that will be reviewed in this chapter. mouse, touchscreen, accelerometer, and gyroscope that will be reviewed in this chapter. It handles the native multitouch protocols on the following platforms: Tuio, WM_Touch, It handles the native multitouch protocols on the following platforms: Tuio, WM_Touch, MacMultitouchSupp

MacMultitouchSupport, ort, MT Protocol A/B, and MT Protocol A/B, and Android.Android. The class of all

The class of all input eveninput events ists is motion eventmotion event. It generates two kinds of events; one of them is. It generates two kinds of events; one of them is touch events

touch events—a motion event that contains at least an—a motion event that contains at least an x x and and y  y  position. All  position. All the touch eventsthe touch events are dispatched across the widget tree. The

are dispatched across the widget tree. The no-touch eventsno-touch events are the rest. The accelerometer is are the rest. The accelerometer is a continuous event, without position. It never starts or

a continuous event, without position. It never starts or stops. These events are not dispatchedstops. These events are not dispatched across the widget tree.

(7)

Using the mouse

Using the mouse

This recipe will teach you how to use the

This recipe will teach you how to use thefifirst kind of input, probably the most used, therst kind of input, probably the most used, the mouse. We will consider the mouse input as a touch event, so the (x, y) position of the touch mouse. We will consider the mouse input as a touch event, so the (x, y) position of the touch (0-1 range) will be scaled

(0-1 range) will be scaled to the window size (width/height) and dispatched to the following:to the window size (width/height) and dispatched to the following:

on_touch_down

on_touch_down

: An event is: An event isfifired when a red when a touch down event is initiated.touch down event is initiated.

Subsequently

Subsequently, , the respective the respective widget'swidget's

on_touch_down()

on_touch_down()

 method is called. method is called.

on_touch_move

on_touch_move

: An event is: An event isfifired when a red when a touch event movtouch event moves (changes location).es (changes location).

Subsequently

Subsequently, , the respective the respective widget'swidget's

on_touch_move()

on_touch_move()

 method is called. method is called.

on_touch_up

on_touch_up

: An event is: An event isfifired when a red when a down event is released (terminated)down event is released (terminated)..

Subsequently

Subsequently, , the respective the respective widget'swidget's

on_touch_up()

on_touch_up()

 method is called. method is called.

Getting ready

Getting ready

In this recipe, we will use the

In this recipe, we will use the Kv language for the design of the widgets, so Kv language for the design of the widgets, so you will need to beyou will need to be familiar with the

familiar with the language or have completed the previous chapterlanguage or have completed the previous chapter. Also, this . Also, this recipe will userecipe will use the common

the common

Button

Button

 widget for reference. widget for reference.

How to do it…

How to do it…

Follow the steps in this

Follow the steps in this recipe:recipe: 1.

1. First, First, let's let's start start with with the the KVKVfifile:le:

<MyW>: <MyW>:

  Button:   Button: id:

id: button1button1 text:

text: 'Hello''Hello'

In the class of the

In the class of the widget in the Python code, we need to override the methodwidget in the Python code, we need to override the method

on_touch_down

on_touch_down

 because the method is already de because the method is already defifined in the ned in the Kivy framework.Kivy framework.

2.

2. Change Change the bthe button utton text text with with the the information information inin

touch.button

touch.button

::

import kivy import kivy

kivy.require('1.9.0') kivy.require('1.9.0') from kivy.app import App from kivy.app import App

from kivy.uix.widget import Widget from kivy.uix.widget import Widget class MyW(Widget):

class MyW(Widget): def

def on_touch_down(self, on_touch_down(self, touch):touch): if

(8)

self.ids.button1.text

self.ids.button1.text = = touch.buttontouch.button class e1App(App):

class e1App(App): def

def build(self):build(self): return

return MyW()MyW()

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

How it works…

How it works…

Let's start with the KV

Let's start with the KV fifile. Thele. The fifirst line is the name of rst line is the name of the rule, similar to the class name inthe rule, similar to the class name in the Python

the Pythonfifile. The second line is the dele. The second line is the defifinition of the button widget, and the third line is nition of the button widget, and the third line is thethe ID of the button, which is

ID of the button, which is necessary to do the call necessary to do the call of the widget inside the Python code, andof the widget inside the Python code, and the fourth line is the de

the fourth line is the defifinition of the text in the button.nition of the text in the button.

With regard to the Python code, the initial four lines are usual

With regard to the Python code, the initial four lines are usual to use Kivy and the buttonto use Kivy and the button widget. Note the

widget. Note the followingfollowingfififth line:fth line:

class MyW(Widget): class MyW(Widget):

This is where we de

This is where we defifine the class associated with our rule in ne the class associated with our rule in the KVthe KVfifile. Now consider thele. Now consider the sixth line:

sixth line:

def on_touch_down(self, touch): def on_touch_down(self, touch):

Here, we start the declaration of the dispatched

Here, we start the declaration of the dispatched

on_touch_down

on_touch_down

 method; you must note the method; you must note the parameter tou

parameter touch in the declaration, and this ch in the declaration, and this parameter is necessary to call the event usingparameter is necessary to call the event using the input—in this case—the mouse. Next, the

the input—in this case—the mouse. Next, the seventh line is:seventh line is:

if

if 'button' 'button' in in touch.profile:touch.profile:

This is a veri

This is a verifification line, because we need to be sure that the input device used in thecation line, because we need to be sure that the input device used in the platform, where we are running our code, supports

platform, where we are running our code, supports the button prothe button profifile. If this line is notle. If this line is not present when the next line is performed, the app could crash. Finally, the eighth line: present when the next line is performed, the app could crash. Finally, the eighth line:

self.ids.button1.text

self.ids.button1.text = = touch.buttontouch.button

This line is where we do

This line is where we do the call to the button prothe call to the button profifile, which gives the information on whichle, which gives the information on which mouse button is touched by the user (the right one, left one, scroll up, and

mouse button is touched by the user (the right one, left one, scroll up, and so on). Using thisso on). Using this information, we change the text in our button that

information, we change the text in our button that has IDhas ID

button1.

button1.

 The last lines of the The last lines of the Python code are usual to run and display our Kivy interface. Just remember that the initial Python code are usual to run and display our Kivy interface. Just remember that the initial part of the

part of the name of the classis as name of the classis as follows:follows:

class e1App(App): class e1App(App):

(9)

Note that it will be the same as the KV

Note that it will be the same as the KVfifile, so the name of the le, so the name of the KVKV fifile in this case isle in this case is

e1.kv

e1.kv

..

A last thing to remark is that

A last thing to remark is that we do not limit the input event to the button, so the touch canwe do not limit the input event to the button, so the touch can occur anywhere within the window.

occur anywhere within the window.

There's more…

There's more…

Another interesting pro

Another interesting profifile that we could call le that we could call for the mouse is thefor the mouse is the

pos

pos

 attribute, which attribute, which provide

provides us with s us with the position vector of the click the position vector of the click in the window. Let's change the in the window. Let's change the seventseventhh line of the Python code to:

line of the Python code to:

self.ids.button1.text

self.ids.button1.text = = str(touch.pos)str(touch.pos)

When we are calling the

When we are calling the

pos

pos

 pro profifile and changing the text in the button widget to the positionle and changing the text in the button widget to the position where the click is per

where the click is per formed, theformed, the

str()

str()

 built-in object is important because the built-in object is important because the

touch.pos

touch.pos

return is a

return is a vectorvector. This means that . This means that we need to convert to a we need to convert to a string to avoid compatibility issues.string to avoid compatibility issues.

See also

See also

If you want to run your interface, take a look at our recipe

If you want to run your interface, take a look at our recipe Running your codeRunning your code. To get further. To get further details about widgets, see the recipes in

details about widgets, see the recipes in Chapter 4Chapter 4,, WidgetsWidgets..

Evolv

Evolv

ing to the

ing to the

touchscreen

touchscreen

In this recipe, we are evolving to the touchscreen. Here, you will see the basic differences In this recipe, we are evolving to the touchscreen. Here, you will see the basic differences between the mouse and the touchscreen. This will give us more options than with the between the mouse and the touchscreen. This will give us more options than with the mouse device.

mouse device.

Getting ready

Getting ready

For this recipe, we will use the Kv language for the design

For this recipe, we will use the Kv language for the design of the widgets, so make sure thatof the widgets, so make sure that you are con

you are confifident with it and refresh your knowledge if necessary. Also, this recipe will dent with it and refresh your knowledge if necessary. Also, this recipe will use theuse the common button and label widgets for reference. Obviously, to get more bene

common button and label widgets for reference. Obviously, to get more benefifit, a t, a touchscreentouchscreen device is useful to run the code.

device is useful to run the code.

How to do it…

How to do it…

Perform the following steps: Perform the following steps:

1.

1. In In the the KVKV fifile, declare the button and the label:le, declare the button and the label:

<MyW>: <MyW>:

  Button:   Button: id:

(10)

text:

text: 'Hello''Hello'   Label:

  Label: id:

id: label1label1 pos:

pos: 100, 100, 100100 text:

text: 'My 'My label label before before press press the the screen'screen'

2.

2. In the In the class of the class of the widget in widget in the Python the Python code, we code, we need tneed to ovo override the erride the methodmethod

on_touch_down

on_touch_down

3.

3. Change Change the buthe button tton text text with with the the information information inin

touch.button

touch.button

4.

4. Change Change the labethe label tl text ext with with the the information information inin

touch.pressure

touch.pressure

import kivy import kivy

kivy.require('1.9.0') kivy.require('1.9.0') from kivy.app import App from kivy.app import App

from kivy.uix.widget import Widget from kivy.uix.widget import Widget class MyW(Widget):

class MyW(Widget): def

def on_touch_down(self, on_touch_down(self, touch):touch): if

if 'button' 'button' in in touch.profile:touch.profile: self.ids.button1.text

self.ids.button1.text = = touch.buttontouch.button if 'pressure' in touch.profile: if 'pressure' in touch.profile: self.ids.label1.text self.ids.label1.text =\=\   str(touch.pressure)   str(touch.pressure) class e2App(App): class e2App(App): def

def build(self):build(self): return

return MyW()MyW()

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

How it works…

How it works…

Well, let's

Well, let'sfifirst review the KVrst review the KV fifile. Thele. Thefifirst line is the name of the rule, the same as of the classrst line is the name of the rule, the same as of the class in the Python

in the Pythonfifile. The second line is the dele. The second line is the defifinition of the button widget, the third line is the IDnition of the button widget, the third line is the ID of the button, which is necessary to do

of the button, which is necessary to do the call of the the call of the widget inside the Python code, and thewidget inside the Python code, and the fourth line is the de

fourth line is the defifinition of the text in nition of the text in the button. Thethe button. The fififth line is the defth line is the defifinition of the labelnition of the label widget. The sixth line is where we give the

widget. The sixth line is where we give the ID to the label, the ID to the label, the seventseventh line is where we give theh line is where we give the position to the label. I should point out that

position to the label. I should point out that the button is using the default position (0, 0), sothe button is using the default position (0, 0), so we will have to give a different position to the label widget to avoid overlapping. The eight is we will have to give a different position to the label widget to avoid overlapping. The eight is the de

(11)

With regard to the Python code, the initial four lines are usual to use

With regard to the Python code, the initial four lines are usual to use Kivy and the widgets.Kivy and the widgets. Note the

Note thefififth one:fth one:

class MyW(Widget): class MyW(Widget):

This is where we de

This is where we defifine the class associated with our rule in ne the class associated with our rule in the KVthe KVfifile. The sixth line:le. The sixth line:

def on_touch_down(self, touch): def on_touch_down(self, touch):

Here, we start the declaration of the dispatched

Here, we start the declaration of the dispatched

on_touch_down

on_touch_down

 method. You must note the method. You must note the parameter tou

parameter touch in the declaration as ch in the declaration as this parameter is necessary to call the event, which isthis parameter is necessary to call the event, which is done by the input (in this case, the mouse). The seventh line is:

done by the input (in this case, the mouse). The seventh line is:

if

if 'button' 'button' in in touch.profile:touch.profile:

It is a veri

It is a verifification line because we need to be sure that the input device used in the cation line because we need to be sure that the input device used in the platform,platform, where we are running our code,

where we are running our code, supports the button prosupports the button profifile. If this line ile. If this line is not present when thes not present when the next one is performed, the app could crash. The eighth

next one is performed, the app could crash. The eighth line is:line is:

self.ids.button1.text

self.ids.button1.text = = touch.buttontouch.button

This line is where we do

This line is where we do the call to the prothe call to the profifile button, which gives the le button, which gives the information of whatinformation of what button is touched by the user (the right, left,

button is touched by the user (the right, left, scroll up button, and so on) and we changedscroll up button, and so on) and we changed the text in the button with the ID

the text in the button with the ID

button1

button1

 with that information. The ninth line is: with that information. The ninth line is:

if 'pressure' in touch.profile: if 'pressure' in touch.profile:

This is the other veri

This is the other verifification line and is important because, due cation line and is important because, due to the fact that pressureto the fact that pressure is speci

is specifific to some touchscreen devices, it is c to some touchscreen devices, it is necessary to avoid crashes. The necessary to avoid crashes. The tenth andtenth and eleventh line: eleventh line: self.ids.label1.text =\ self.ids.label1.text =\ str(touch.pressure) str(touch.pressure)

Those lines are where we change the text of the label

Those lines are where we change the text of the label to the pressure value of theto the pressure value of the speci

specifific touch.c touch.

The last lines of the

The last lines of the Python code are usual to run and display our Kivy interface. JustPython code are usual to run and display our Kivy interface. Just remember that the initial part of the name of the class is:

remember that the initial part of the name of the class is:

class e2App(App): class e2App(App):

It will be the

It will be the same in relation to the KVsame in relation to the KV fifile. For example, the name of the KVle. For example, the name of the KVfifile in this casele in this case is

is

e2.kv

e2.kv

.. The

The fifinal thing to remark is that we do nal thing to remark is that we do not limit the input event to the buttonnot limit the input event to the button, so the touch can, so the touch can occur anywhere within the window or the

(12)

There's more…

There's more…

Actually, your device could have more pro

Actually, your device could have more profifiles than we saw in this recipe. Let's les than we saw in this recipe. Let's change thechange the code to know that for your speci

code to know that for your specifific device. Remove the ninth line and chac device. Remove the ninth line and change the tenth andnge the tenth and eleventh lines to:

eleventh lines to:

self.ids.label1.text =\ self.ids.label1.text =\ str(touch.profile)

str(touch.profile)

These lines will change the l

These lines will change the label's text for all the proabel's text for all the profifiles available for your device. Thus, youles available for your device. Thus, you can get more yield of your app.

can get more yield of your app.

See also

See also

If you want to run

If you want to run your interface, take a look ayour interface, take a look at our recipe Running your code, and t our recipe Running your code, and to get moreto get more detail about widgets, see the recipes in

detail about widgets, see the recipes in Chapter 4Chapter 4,, WidgetsWidgets. If you want to run the code in a. If you want to run the code in a mobile device, see

mobile device, see Chapter 9Chapter 9,, Kivy for Mobile DevicesKivy for Mobile Devices..

Working with the accelerometer 

Working with the accelerometer 

Nowadays, it is common that mobile devices are equipped with an accelerometer. Thereby, Nowadays, it is common that mobile devices are equipped with an accelerometer. Thereby, it is

it is relevant to consider this input to develop fancy apps. The arelevant to consider this input to develop fancy apps. The a ccelerometccelerometer is one er is one kind ofkind of event that is considered as a no-touch event because it has neither start nor an

event that is considered as a no-touch event because it has neither start nor an end, it isend, it is always providing information.

always providing information.

Getting ready

Getting ready

In this recipe, we will use the

In this recipe, we will use the Kv language for the design of the widgets, so, Kv language for the design of the widgets, so, again, you willagain, you will need to be familiar with the Kv

need to be familiar with the Kv language. Also, this recipe will use the language. Also, this recipe will use the common button andcommon button and label widgets for reference. Obviously, to get more bene

label widgets for reference. Obviously, to get more benefifit, a device with an at, a device with an accelerometccelerometer iser is useful to run the code.

useful to run the code. It is necessary to install

It is necessary to install a package for the use of the a package for the use of the accelerometaccelerometer in any mobile device;er in any mobile device; there is a way to deal with

there is a way to deal with every specievery specifific device, but we do not have to reinvent the wheel.c device, but we do not have to reinvent the wheel. Let's use a

Let's use a

Plyer

Plyer

 package, which is an effort from many of the Kivy developers. To install package, which is an effort from many of the Kivy developers. To install the package from the shell, use:

the package from the shell, use:

$ sudo pip plyer install $ sudo pip plyer install

Here where we are using

Here where we are using

pip

pip

 to install the to install the

Plyer

Plyer

 package, if you do not have package, if you do not have

pip

pip

 installed in installed in your computer, see the recipe

(13)

How to do it…

How to do it…

To complete this recipe, follow these steps: To complete this recipe, follow these steps:

1.

1. In In the the KVKV fifile, dele, defifine the four labels and the button:ne the four labels and the button:

<Accel>: <Accel>:   Label:   Label:

id:

id: label1label1 pos: pos: 150, 150, 300300 text: text: 'X: 'X: ''   Label:   Label: id:

id: label2label2 pos:

pos: 150, 150, 250250 text:

text: 'Y: 'Y: ''   Label:

  Label: id:

id: label3label3 pos: pos: 150, 150, 200200 text: text: 'Z: 'Z: ''   Label:   Label: id:

id: statusstatus pos: pos: 150, 150, 150150 text: text: ''''   Button:   Button: id:

id: button1button1 pos:

pos: 150, 150, 5050 text:

text: 'Start''Start' on_press:

on_press: root.pressed1()root.pressed1()

2.

2. In In the the PythonPythonfifile, import the usual packages to use Kivys.le, import the usual packages to use Kivys. 3.

3. Import Import thethe

Clock

Clock

 and and

Plyer

Plyer

 packages. packages. 4.

4. In In the the class class for for the the rule, rule, dedefifine a class to standby the accelerometer.ne a class to standby the accelerometer. 5. De

5. Defifine the method to start to retrieve data from the accelerometer.ne the method to start to retrieve data from the accelerometer. 6. De

6. Defifine the method when the button is pressed:ne the method when the button is pressed:

from kivy.app import App from kivy.app import App

from kivy.properties import ObjectProperty from kivy.properties import ObjectProperty from kivy.uix.widget import Widget

(14)

from kivy.clock import Clock from kivy.clock import Clock from plyer import accelerometer from plyer import accelerometer class Accel(Widget):

class Accel(Widget): def

def __init__(self):__init__(self): super(Accel,

super(Accel, self).__init__()self).__init__() self.sensorEnabled

self.sensorEnabled = = FalseFalse def

def get_acceleration(self, get_acceleration(self, dt):dt): val

val = = accelerometer.accelerationaccelerometer.acceleration self.ids.label1.text

self.ids.label1.text = = "X: "X: " " + + str(val[0])str(val[0]) self.ids.label2.text

self.ids.label2.text = = "Y: "Y: " " + + str(val[1])str(val[1]) self.ids.label3.text

self.ids.label3.text = = "Z: "Z: " " + + str(val[2])str(val[2]) def

def pressed1(self):pressed1(self):   try:

  try: if

if not not self.sensorEnabled:self.sensorEnabled:   accelerometer.enable()   accelerometer.enable()   Clock.schedule_interval(self.get_acceleration,   Clock.schedule_interval(self.get_acceleration, 1 / 20.) 1 / 20.) self.sensorEnabled

self.sensorEnabled = = TrueTrue self.ids.button1.text

self.ids.button1.text = = "Stop""Stop"

  else:   else:   accelerometer.disable()   accelerometer.disable()   Clock.unschedule(self.get_acceleration)   Clock.unschedule(self.get_acceleration) self.sensorEnabled

self.sensorEnabled = = FalseFalse self.ids.button1.text

self.ids.button1.text = = "Start""Start" except

except NotImplementedError:NotImplementedError: import

import traceback; traceback; traceback.print_exc()traceback.print_exc() self.ids.status.text

self.ids.status.text =\=\ "Accelerometer

"Accelerometer is is not not supported supported for for your your platform"platform" class e3App(App):

class e3App(App): def

def build(self):build(self): return

return Accel()Accel() if __name__ == '__main__': if __name__ == '__main__':   e3App().run()

(15)

How it works…

How it works…

First, review the KV

First, review the KV fifile. Note that thele. Note that the fifirst line is the rst line is the name of the rule, similar to the class name of the rule, similar to the class inin the Python

the Pythonfifile. Included in the next lines are the dele. Included in the next lines are the defifinitions of the four labels that we will use,nitions of the four labels that we will use, so note the text of the label with the ID

so note the text of the label with the ID status. It will likely be blank, but status. It will likely be blank, but it will be visible it will be visible onlyonly when we modify this

when we modify thisfifield from the Python code.eld from the Python code. In the Python code, the

In the Python code, thefifirst three lines are usual to importrst three lines are usual to import

kivy

kivy

 and the widgets. and the widgets. The fourth line:

The fourth line:

from kivy.clock import Clock from kivy.clock import Clock

This will import the

This will import the clock, which is used to get clock, which is used to get the accelerometthe accelerometer value in a time lap er value in a time lap because,because, as we already said, this

as we already said, this input is continuously proinput is continuously providing data. Theviding data. The fififth line:fth line:

from plyer import accelerometer from plyer import accelerometer

This is importing the package

This is importing the package

plyer

plyer

, which is the , which is the one that makes it possible to retrieve theone that makes it possible to retrieve the data from an iOS or Android device. The sixth line:

data from an iOS or Android device. The sixth line:

class Accel(Widget): class Accel(Widget):

This is the line

This is the line where the class for the rule starts. where the class for the rule starts. Its name must be the same as the Its name must be the same as the Kivy rule.Kivy rule. The seventh, eighth, and ninth lines are:

The seventh, eighth, and ninth lines are:

def

def __init__(self):__init__(self): super(Accel,

super(Accel, self).__init__()self).__init__() self.sensorEnabled

self.sensorEnabled = = FalseFalse

These de

These defifine the method that initializes the class ne the method that initializes the class and put in standby the accelerometer to beand put in standby the accelerometer to be used later. The tenth, eleven

used later. The tenth, eleventh, twelfth, th, twelfth, thirteenth, and fourteenth lines are:thirteenth, and fourteenth lines are:

def

def get_acceleration(self, get_acceleration(self, dt):dt): val

val = = accelerometer.accelerationaccelerometer.acceleration self.ids.label1.text

self.ids.label1.text = = "X: "X: " " + + str(val[0])str(val[0]) self.ids.label2.text

self.ids.label2.text = = "Y: "Y: " " + + str(val[1])str(val[1]) self.ids.label3.text

self.ids.label3.text = = "Z: "Z: " " + + str(val[2])str(val[2])

These lines are used to retrieve the data of the accelerometer and will modify the text of the These lines are used to retrieve the data of the accelerometer and will modify the text of the

first three labels with the rst three labels with the data of the acceleration. Now, look at thedata of the acceleration. Now, look at thefififteenth line:fteenth line:

def pressed1(self): def pressed1(self):

This is where we de

This is where we defifine the method perne the method performed when the button is pressed. In formed when the button is pressed. In the sixteenththe sixteenth line, we start a

line, we start a

try

try

 sentence to start getting data from the accelerometer. In the seventeenth sentence to start getting data from the accelerometer. In the seventeenth line, it is shown that if

line, it is shown that if the accelerometethe accelerometer is disabled, enable it r is disabled, enable it or vice versa. The eighteenthor vice versa. The eighteenth line is:

line is:

Clock.schedule_interval(self.get_acceleration, 1 / 20.) Clock.schedule_interval(self.get_acceleration, 1 / 20.)

(16)

In this line, we do the

In this line, we do the acquisition of the acceleration in time intervals. The acceleration isacquisition of the acceleration in time intervals. The acceleration is acquired by calling the

acquired by calling the

get_acceleration

get_acceleration

 method. The next class is usual to display our method. The next class is usual to display our Kivy interface.

Kivy interface.

There's more…

There's more…

Also, the

Also, the

plyer

plyer

 package allows you to interact with the compass and the GPS of  package allows you to interact with the compass and the GPS of the mobilethe mobile device using a similar procedure. In the case of the compass, it is

device using a similar procedure. In the case of the compass, it is very easy to change.very easy to change. The change in the code is

The change in the code is the wordthe word

gyroscope

gyroscope

 for for

compass

compass

 and and

acceleration

acceleration

 for for

orientation

orientation

..

See also

See also

To get more details about widgets, see the

To get more details about widgets, see the recipes inrecipes in Chapter 4Chapter 4,, WidgetsWidgets, and if you want to, and if you want to run the code in a mobile device, see

run the code in a mobile device, see Chapter 9Chapter 9,, Kivy for Mobile DevicesKivy for Mobile Devices..

Using the gyroscope

Using the gyroscope

Mobile devices today also have a gyroscope. The gyroscope is

Mobile devices today also have a gyroscope. The gyroscope is considered as a considered as a no-touch evenno-touch event.t. This kind of event does not have a start or

This kind of event does not have a start or an end; it is alan end; it is always proways providing information.viding information.

Getting ready

Getting ready

For this recipe, we will use the Kv language for the design

For this recipe, we will use the Kv language for the design of the widgets. Also, this recipe willof the widgets. Also, this recipe will use the common button and label

use the common button and label widgets for reference. Obviouslywidgets for reference. Obviously, to run the , to run the code of thiscode of this recipe properly

recipe properly, a device , a device with a gyroscope is with a gyroscope is necessary.necessary. It is necessary to install

It is necessary to install a package to use the gyroscope with any mobile device. While there isa package to use the gyroscope with any mobile device. While there is a way to deal with speci

a way to deal with specifific devices, we do not have to reinvent the wheel. Let's use thec devices, we do not have to reinvent the wheel. Let's use the

plyer

plyer

package, which is an ef

package, which is an effort from many of the Kivy developers. Tfort from many of the Kivy developers. To install the package from theo install the package from the shell, use:

shell, use:

$ sudo pip plyer install $ sudo pip plyer install

How to do it…

How to do it…

To complete this recipe, follow these steps: To complete this recipe, follow these steps:

1.

1. In In the the KVKV fifile, dele, defifine the four labels and the button:ne the four labels and the button:

<Acce>: <Acce>:   Label:   Label:

id:

id: label1label1 pos:

(17)

text:

text: 'X: 'X: ''   Label:

  Label: id:

id: label2label2 pos:

pos: 150, 150, 250250 text:

text: 'Y: 'Y: ''   Label:

  Label: id:

id: label3label3 pos: pos: 150, 150, 200200 text: text: 'Z: 'Z: ''   Label:   Label: id:

id: statusstatus pos: pos: 150, 150, 150150 text: text: ''''   Button:   Button: id:

id: button1button1 pos:

pos: 150, 150, 5050 text:

text: 'Start''Start' on_press:

on_press: root.pressed1()root.pressed1()

2.

2. In In the the PythonPythonfifile, import the usual packages to use Kivy.le, import the usual packages to use Kivy. 3.

3. Import Import thethe

Clock

Clock

 and and

plyer

plyer

 packages. packages. 4.

4. In In the the class class for for the the rule, rule, dedefifine a class to stand by the ne a class to stand by the gyroscope.gyroscope. 5. De

5. Defifine the method to starne the method to star t to retrieve data from the gyroscope.t to retrieve data from the gyroscope. 6. De

6. Defifine the method when the button is pressed:ne the method when the button is pressed:

from kivy.app import App from kivy.app import App

from kivy.properties import ObjectProperty from kivy.properties import ObjectProperty from kivy.uix.widget import Widget

from kivy.uix.widget import Widget from kivy.clock import Clock

from kivy.clock import Clock from plyer import gyroscope from plyer import gyroscope class Acce(Widget):

class Acce(Widget): def

def __init__(self):__init__(self): super(Acce,

super(Acce, self).__init__()self).__init__() self.sensorEnabled

self.sensorEnabled = = FalseFalse def

def get_orientation(self, get_orientation(self, dt):dt): val

(18)

self.ids.label1.text

self.ids.label1.text = = "X: "X: " " + + str(val[0])str(val[0]) self.ids.label2.text

self.ids.label2.text = = "Y: "Y: " " + + str(val[1])str(val[1]) self.ids.label3.text

self.ids.label3.text = = "Z: "Z: " " + + str(val[2])str(val[2]) def

def pressed1(self):pressed1(self):   try:

  try: if

if not not self.sensorEnabled:self.sensorEnabled:   gyroscope.enable()   gyroscope.enable()   Clock.schedule_interval(self.get_orientation,   Clock.schedule_interval(self.get_orientation, 1 / 20.) 1 / 20.) self.sensorEnabled

self.sensorEnabled = = TrueTrue self.ids.button1.text

self.ids.button1.text = = "Stop""Stop"

  else:   else:   gyroscope.disable()   gyroscope.disable()   Clock.unschedule(self.get_orientation)   Clock.unschedule(self.get_orientation) self.sensorEnabled

self.sensorEnabled = = FalseFalse self.ids.button1.text

self.ids.button1.text = = "Start""Start" except

except NotImplementedError:NotImplementedError: import

import traceback; traceback; traceback.print_exc()traceback.print_exc() self.ids.status.text

self.ids.status.text =\=\ "Gyroscope

"Gyroscope is is not not supported supported for for your your platform"platform" class e4App(App):

class e4App(App): def

def build(self):build(self): return

return Acce()Acce()

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

How it works…

How it works…

The KV

The KVfifile that we are using is le that we are using is similar to the last recipe's KVsimilar to the last recipe's KVfifile. We dele. We defifine four labels andne four labels and the start button.

the start button.

In the Python code, the

In the Python code, thefifirst three lines are usual to importrst three lines are usual to import

kivy

kivy

 and the widgets. and the widgets. The fourth line:

The fourth line:

from kivy.clock import Clock from kivy.clock import Clock

We are importing the clock, which is

We are importing the clock, which is used to get the accelerometer value in a time lapused to get the accelerometer value in a time lap because, as we already said, this

because, as we already said, this input is continuously proinput is continuously providing data. Theviding data. Thefififth line:fth line:

from plyer import gyroscope from plyer import gyroscope

(19)

This is importing the package

This is importing the package

plyer

plyer

, which is the , which is the one that makes it possible to retrieve theone that makes it possible to retrieve the data from an iOS or Android device. The sixth line:

data from an iOS or Android device. The sixth line:

class Acce(Widget): class Acce(Widget):

It is the line where the class for the rule starts and its name must be the same as in the Kivy It is the line where the class for the rule starts and its name must be the same as in the Kivy rule. The seventh, eighth, and ninth lines are:

rule. The seventh, eighth, and ninth lines are:

def

def __init__(self):__init__(self): super(Acce,

super(Acce, self).__init__()self).__init__() self.sensorEnabled

self.sensorEnabled = = FalseFalse

Those are where we de

Those are where we defifine the methods that initialize the class ne the methods that initialize the class and put the accelerometerand put the accelerometer on standby to be used

on standby to be used laterlater. The tenth, eleventh, twelfth, thir. The tenth, eleventh, twelfth, thir teenth, and fourteenth linesteenth, and fourteenth lines are as follows:

are as follows:

def

def get_orientation(self, get_orientation(self, dt):dt): val

val = = gyroscope.orientationgyroscope.orientation self.ids.label1.text

self.ids.label1.text = = "X: "X: " " + + str(val[0])str(val[0]) self.ids.label2.text

self.ids.label2.text = = "Y: "Y: " " + + str(val[1])str(val[1]) self.ids.label3.text

self.ids.label3.text = = "Z: "Z: " " + + str(val[2])str(val[2])

Those lines are a

Those lines are allowing us to retrieve data from the gyroscope and enabling llowing us to retrieve data from the gyroscope and enabling us to modify theus to modify the text of the

text of thefifirst three labels with the rst three labels with the data of the orientation. Thedata of the orientation. Thefififteenth line:fteenth line:

def pressed1(self): def pressed1(self):

It is where we de

It is where we defifine the method perne the method performed when the button is pressed. In formed when the button is pressed. In the sixteenththe sixteenth line, we start a

line, we start a

try

try

 sentence to start  sentence to start to get data to get data from the gyroscope. With the seventeenthfrom the gyroscope. With the seventeenth line, we can open an

line, we can open an

if

if

 sentence for the case that the gyroscope is unable, enable it. sentence for the case that the gyroscope is unable, enable it. The eighteenth line:

The eighteenth line:

Clock.schedule_interval(self.get_orientation, 1 / 20.) Clock.schedule_interval(self.get_orientation, 1 / 20.)

In this line, we can get

In this line, we can get the intervals of the orientation by calling thethe intervals of the orientation by calling the

get_orientation

get_orientation

method. The next class is the usual one to display our Kivy interface. method. The next class is the usual one to display our Kivy interface.

See also

See also

If you want to run the code in a

(20)

The differences between the touch and

The differences between the touch and

motion events

motion events

There is a key difference between touch and motion events. A motion event is a continuous There is a key difference between touch and motion events. A motion event is a continuous succession of many touch events. However, we also know that a touch event always has succession of many touch events. However, we also know that a touch event always has the

the

pos

pos

 pro profifile, namelyle, namely position informationposition information. The motion event, however, is not dispatched. The motion event, however, is not dispatched throughout the widget tree.

throughout the widget tree.

Getting ready

Getting ready

In this recipe, we will use the

In this recipe, we will use the Kv language for the design of the widgets, so Kv language for the design of the widgets, so we assume thatwe assume that the reader is familiar with the Kv language or did the lecture of the

the reader is familiar with the Kv language or did the lecture of thefifirst chapter. Also, thisrst chapter. Also, this recipe will use the

recipe will use the common button widget for referencommon button widget for reference.ce.

How to do it…

How to do it…

Use this recipe

Use this recipe and follow these steps:and follow these steps: 1.

1. First, First, in in the the KVKVfifile, dele, defifine a button:ne a button:

<MyW>: <MyW>:

  Button:   Button: id:

id: button1button1 pos:

pos: 0,00,0 text:

text: 'Hello''Hello'

2.

2. In the In the class of the class of the widget in widget in the Python the Python code, we code, we need tneed to ovo override the erride the methodmethod

on_touch_move

on_touch_move

.. 3.

3. Change Change the buthe button's tton's position position with with the the information information inin

touch.pos

touch.pos

::

import kivy import kivy

kivy.require('1.9.0') kivy.require('1.9.0') from kivy.app import App from kivy.app import App

from kivy.uix.widget import Widget from kivy.uix.widget import Widget class MyW(Widget):

class MyW(Widget): def

def on_touch_move(self, on_touch_move(self, touch):touch): if

if 'pos' 'pos' in in touch.profile:touch.profile: self.ids.button1.pos

self.ids.button1.pos = = touch.postouch.pos class e5App(App):

(21)

def

def build(self):build(self): return

return MyW()MyW()

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

How it works…

How it works…

Let's start with the KV

Let's start with the KV fifile, thele, thefifirst line is the rst line is the name of the rule, similar to the class name of the rule, similar to the class in thein the Python

Pythonfifile. The second line is the dele. The second line is the defifinition of the button widget, the third line is the nition of the button widget, the third line is the ID of theID of the button, which is necessary to do the call

button, which is necessary to do the call of the widget inside the Python code, of the widget inside the Python code, the fourth linethe fourth line speci

specififies the initial position of the button, and thees the initial position of the button, and the fififth line is the defth line is the defifinition of the text innition of the text in the button.

the button.

In the Python code, the initial

In the Python code, the initial four lines are usual to use Kivy and the button widget.four lines are usual to use Kivy and the button widget. The

Thefififth one:fth one:

class MyW(Widget): class MyW(Widget):

It is where we de

It is where we defifine the class associated with our rule in ne the class associated with our rule in the KVthe KVfifile. The sixth line:le. The sixth line:

def on_touch_move(self, touch): def on_touch_move(self, touch):

Here, we start the declaration of the dispatched

Here, we start the declaration of the dispatched

on_touch_move

on_touch_move

 method; you must note the method; you must note the parameter tou

parameter touch in the declaration, as ch in the declaration, as this parameter is necessary to call the event using thethis parameter is necessary to call the event using the input. Now the seventh line:

input. Now the seventh line:

if

if 'pos' 'pos' in in touch.profile:touch.profile:

This is a veri

This is a verifification line, because we need to be sure that the input device used in thecation line, because we need to be sure that the input device used in the platform, where we are running our code, supports

platform, where we are running our code, supports the button prothe button profifile. If this line is notle. If this line is not present when the next one is performed, the app could crash. The eighth

present when the next one is performed, the app could crash. The eighth line:line:

self.ids.button1.pos

self.ids.button1.pos = = touch.postouch.pos

This line is where we do

This line is where we do the call to the prothe call to the profifile position, which le position, which gives the information of wheregives the information of where the touch occurs, and we changed the position of the

the touch occurs, and we changed the position of the button with the IDbutton with the ID

button1

button1

 with that with that informatio

information. The last lines of n. The last lines of the Python code are usual to run and display our Kivy interface.the Python code are usual to run and display our Kivy interface. Just remember that the initial part of the name of the class is:

Just remember that the initial part of the name of the class is:

class e5App(App): class e5App(App):

It will be same as the KV

It will be same as the KVfifile; the name of the KVle; the name of the KV fifile in this case isle in this case is

e5.kv

e5.kv

..

The last thing to remark is that

The last thing to remark is that we do not limit the input event to the button, so the touch canwe do not limit the input event to the button, so the touch can occur anywhere in the window.

(22)

There's more…

There's more…

Also, the motion events are compatible with the

Also, the motion events are compatible with the touch eventtouch event. It . It is possible to add is possible to add to our codeto our code to the class

to the class

MyW

MyW

 a a

on_touch_down

on_touch_down

 method like this: method like this:

def on_touch_down(self, touch): def on_touch_down(self, touch):

if

if 'button' 'button' in in touch.profile:touch.profile: self.ids.button1.text

self.ids.button1.text = = touch.buttontouch.button

With this addition, now when you touch the text inside, the button is going to change to the With this addition, now when you touch the text inside, the button is going to change to the information about which button is used.

information about which button is used.

See also

See also

To get more details about widgets, see the

To get more details about widgets, see the recipes inrecipes inChapter 4Chapter 4,, WidgetsWidgets..

Recognizing touch shapes

Recognizing touch shapes

There is a useful tool provided by Kivy that permits us to recognize the shape of the

There is a useful tool provided by Kivy that permits us to recognize the shape of the touch thattouch that is performed. In this recipe, we will go

is performed. In this recipe, we will go through the foundationthrough the foundations of using it.s of using it.

Getting ready

Getting ready

In this recipe, we will use the

In this recipe, we will use the Kv language for the design of the widgets, so Kv language for the design of the widgets, so we assume thatwe assume that the reader is familiar with

the reader is familiar with the Kv language. Also, this recipe will the Kv language. Also, this recipe will use the common button anduse the common button and label widgets

label widgets for reference.for reference.

How to do it…

How to do it…

Follow these steps: Follow these steps:

1.

1. First, First, in in the the KVKVfifile, dele, defifine a button and an empty label:ne a button and an empty label:

<MyW>: <MyW>:

  Button:   Button: id:

id: button1button1 pos:

pos: 0,00,0 text:

text: 'Hello''Hello'   Label:

  Label: id:

id: label1label1 pos:

pos: 50, 50, 200200 text:

(23)

2.

2. In the In the class of the class of the widget in widget in the Python the Python code, we code, we need tneed to ovo override the erride the methodmethod

on_touch_move

on_touch_move

.. 3.

3. Change Change the buthe button tton position position to to the the information information inin

touch.pos

touch.pos

.. 4.

4. Change the Change the text text in the in the label when label when a rectangua rectangular shape lar shape is presenis present:t:

import kivy import kivy

kivy.require('1.9.0') kivy.require('1.9.0') from kivy.app import App from kivy.app import App

from kivy.uix.widget import Widget from kivy.uix.widget import Widget from kivy.input.shape import ShapeRect from kivy.input.shape import ShapeRect class MyW(Widget):

class MyW(Widget): def

def on_touch_move(self, on_touch_move(self, touch):touch): if

if 'pos' 'pos' in in touch.profile:touch.profile: self.ids.button1.pos

self.ids.button1.pos = = touch.postouch.pos if

if isinstance(touch.shape, isinstance(touch.shape, ShapeRect):ShapeRect): self.ids.label1.text

self.ids.label1.text =\=\

'My touch have a rectangle shape of size' + str(touch.shape. 'My touch have a rectangle shape of size' + str(touch.shape. width)+ str(touch.shape.height)

width)+ str(touch.shape.height) class e6App(App):

class e6App(App): def

def build(self):build(self): return

return MyW()MyW()

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

How it works…

How it works…

In the KV

In the KVfifile, thele, thefifirst line as usual is the name of the rule. The second line is the derst line as usual is the name of the rule. The second line is the defifinition ofnition of the button widget, the third line is the ID

the button widget, the third line is the ID of the button, which is necessary to do of the button, which is necessary to do the call of thethe call of the widget inside the Python code, the fourth li

widget inside the Python code, the fourth line specine specififies the initial position of the es the initial position of the button, andbutton, and the

thefififth line is the defth line is the defifinition of the text in the button. The sixth line is the nition of the text in the button. The sixth line is the dedefifinition of the labelnition of the label widget, the seventh line is ID of the label, the eighth line is the initial position of the label, and widget, the seventh line is ID of the label, the eighth line is the initial position of the label, and the ninth line is the

the ninth line is the initial text of the label.initial text of the label.

In relation to the Python code, the initial four lines are

In relation to the Python code, the initial four lines are the usual lines to use Kivy and thethe usual lines to use Kivy and the button widget. Next, the

button widget. Next, thefififth one:fth one:

from kivy.input.shape import ShapeRect from kivy.input.shape import ShapeRect

(24)

In this line, we import the

In this line, we import the information ofinformation of

ShapeRect

ShapeRect

 to be compared with the touch to be compared with the touch performed in the app. The sixth line is:

performed in the app. The sixth line is:

class MyW(Widget): class MyW(Widget):

This is where we de

This is where we defifine the class associated with our rule in ne the class associated with our rule in the KVthe KVfifile. The seventh line:le. The seventh line:

def

def on_touch_move(self, on_touch_move(self, touch):touch):

Here, we start the declaration of the dispatched

Here, we start the declaration of the dispatched

on_touch_move

on_touch_move

 method; you must note the method; you must note the parameter tou

parameter touch in the declaration, and this ch in the declaration, and this parameter is necessary to call the event by theparameter is necessary to call the event by the input. The eighth and ninth lines are:

input. The eighth and ninth lines are:

if

if 'pos' 'pos' in in touch.profile:touch.profile: self.ids.button1.pos

self.ids.button1.pos = = touch.postouch.pos

Those lines change the position of the button. The tenth line is: Those lines change the position of the button. The tenth line is:

if

if isinstance(touch.shape, isinstance(touch.shape, ShapeRect):ShapeRect):

It is where the comparison between the imported shape and the shape of

It is where the comparison between the imported shape and the shape of the touch isthe touch is performed. The eleventh line will change the label text with the dimension of the touch if performed. The eleventh line will change the label text with the dimension of the touch if thisthis is rectangular. The last lines of the Python code are the

is rectangular. The last lines of the Python code are the usual lines to run and display our Kivyusual lines to run and display our Kivy interface. Just remember that the initial part of the name of the class is:

interface. Just remember that the initial part of the name of the class is:

class e6App(App): class e6App(App):

It will be the same of the KV

It will be the same of the KVfifile; the name of the KVle; the name of the KV fifile in this case isle in this case is

e6.kv

e6.kv

See also

See also

If you want to run your interface, take a look at our recipe

If you want to run your interface, take a look at our recipe Running your codeRunning your code, and to get more, and to get more details about widgets, see the recipes in

details about widgets, see the recipes in Chapter 4Chapter 4,, WidgetsWidgets..

Detecting multitapping

Detecting multitapping

The multitapping detection is a useful tool in the development of an app. When more than a The multitapping detection is a useful tool in the development of an app. When more than a touch occurs in a zone, it is what we call a

touch occurs in a zone, it is what we call a multitapmultitap..

Getting ready

Getting ready

We will work with the

We will work with the

on_touch_down

on_touch_down

 method, so it could be  method, so it could be useful to go through the recipeuseful to go through the recipe Evolving to the touchscreen

Evolving to the touchscreen in this chapter. Also, this recipe will use the  in this chapter. Also, this recipe will use the common buttocommon button andn and label widgets

(25)

How to do it…

How to do it…

Follow these steps in this recipe: Follow these steps in this recipe:

1.

1. First, First, in in the the KVKVfifile, dele, defifine a button and an empty label:ne a button and an empty label:

<MyW>: <MyW>:

  Button:   Button: id:

id: button1button1 pos:

pos: 0,00,0 text:

text: 'Hello''Hello'   Label:

  Label: id:

id: label1label1 pos:

pos: 200, 200, 200200 text:

text: ''''

2.

2. In the In the class of the class of the widget in widget in the Python the Python code, we code, we need tneed to ovo override the erride the methodmethod

on_touch_down

on_touch_down

.. 3.

3. Change the Change the text text in the in the label when label when a double a double tap is tap is present.present. 4.

4. Change the Change the text text in the in the label when label when a triple a triple tap is tap is present:present:

import kivy import kivy

kivy.require('1.9.0') kivy.require('1.9.0') from kivy.app import App from kivy.app import App

from kivy.uix.widget import Widget from kivy.uix.widget import Widget class MyW(Widget):

class MyW(Widget): def

def on_touch_down(self, on_touch_down(self, touch):touch): if touch.is_double_tap: if touch.is_double_tap:

self.ids.label1.text

self.ids.label1.text = = 'Touch 'Touch is is a a double double tap tap !! - The interval is: '+

- The interval is: '+

str(touch.double_tap_time) str(touch.double_tap_time) elif

elif touch.is_triple_tap:touch.is_triple_tap: self.ids.label1.text

self.ids.label1.text = = "Touch "Touch is is a a triple triple tap tap !! - The interval is: {0} \nand distance between - The interval is: {0} \nand distance between previous is {1}".format(touch.triple_tap_time, previous is {1}".format(touch.triple_tap_time, touch.triple_tap_distance) touch.triple_tap_distance) class e7App(App): class e7App(App): def

def build(self):build(self): return

return MyW()MyW()

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

(26)

How it works…

How it works…

We are again using our KV

We are again using our KVfifile with a simple button and empty label with the le with a simple button and empty label with the IDID

button1

button1

 and and

label1

label1

 respectively. respectively.

In the Python code, the initial

In the Python code, the initial four lines are usual to use Kivy and the button widget. Thefour lines are usual to use Kivy and the button widget. Thefififthfth line is:

line is:

class MyW(Widget): class MyW(Widget):

It is where we de

It is where we defifine the class associated with our rule in ne the class associated with our rule in the KVthe KVfifile. The sixth line is:le. The sixth line is:

def on_touch_down(self, touch): def on_touch_down(self, touch):

Here, we start the declaration of the dispatched

Here, we start the declaration of the dispatched

on_touch_down

on_touch_down

 method; you must note the method; you must note the parameter tou

parameter touch in the declaration and this ch in the declaration and this parameter is necessary to call the event by theparameter is necessary to call the event by the input. The seventh and eighth lines

input. The seventh and eighth lines are:are:

if touch.is_double_tap: if touch.is_double_tap:

self.ids.label1.text = 'Touch is a double tap ! - The self.ids.label1.text = 'Touch is a double tap ! - The interval is: '+ str(touch.double_tap_time)

interval is: '+ str(touch.double_tap_time)

These lines are where we detect if the tap

These lines are where we detect if the tap is double. If it is is double. If it is true, we change the text of thetrue, we change the text of the label de

label defifined in the KVned in the KVfifile with the stringle with the string

Touch is a double tap!

Touch is a double tap! – The interval

– The interval

is:

is:

 plus the time that the double tap takes. The ninth and tenth lines: plus the time that the double tap takes. The ninth and tenth lines:

elif

elif touch.is_triple_tap:touch.is_triple_tap:

self.ids.label1.text = "Touch is a triple tap ! - The self.ids.label1.text = "Touch is a triple tap ! - The interval is: {0} \nand distance between previous is interval is: {0} \nand distance between previous is

{1}".format(touch.triple_tap_time, touch.triple_tap_distance) {1}".format(touch.triple_tap_time, touch.triple_tap_distance)

Those lines change the text of the label if

Those lines change the text of the label if the touch in a triple tab. the touch in a triple tab. The last lines of the The last lines of the PythonPython code are the usual lines to run and

code are the usual lines to run and display our Kivy interface. Just remember that the initialdisplay our Kivy interface. Just remember that the initial part of the name of the class is:

part of the name of the class is:

class e7App(App): class e7App(App):

It will be similar to the KV

It will be similar to the KVfifile; the name of the KVle; the name of the KVfifile in this case isle in this case is

e7.kv

e7.kv

..

Grabbing

Grabbing

touch ev

touch ev

ents

ents

There are some moments or areas where we do not want the touch performed in the same There are some moments or areas where we do not want the touch performed in the same way. Therefore, we can grab some inputs to give them special treatment.

References

Related documents

Currently, National Instruments leads the 5G Test &amp; Measurement market, being “responsible for making the hardware and software for testing and measuring … 5G, … carrier

Social inequalities, the widening gulf between the rich and the poor, exploitation by the higher castes in Andhra Pradesh and more importantly the loss of self-respect by

A policy in which all of the fixed assets of a firm are financed with long-term capital, but some of the firm’s permanent current assets are financed with short-term

The corona radiata consists of one or more layers of follicular cells that surround the zona pellucida, the polar body, and the secondary oocyte.. The corona radiata is dispersed

[r]

Many of the metabolically related risk factors such as obesity (30) and physical activity (31) as well as family history of colorectal cancer (32) were more strongly associated

Tolfenamic acid inhibits colon cancer cell and tumor growth and induces degradation of speci ficity protein (Sp) transcription factors. The cannabinoid WIN 55,212-2 decreases speci

To determine the expression and localization of the cohesin SA1, IHC was performed on (i) formalin- fixed rectal biopsies (as above) that were embedded in paraf fin blocks, sectioned