Kivy Cookbook

4.8 (5 reviews total)
By Hugo Solis
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Kivy and the Kv Language

About this book

Kivy is an open-source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. It is a promising Python framework to develop UI and UX apps in a cross-platform environment, under the Python philosophy.

Kivy Cookbook is a practical book that will guide you through the Kivy framework to develop apps and get your apps ready for distribution in App Store and Android devices.

You will start off with installing Kivy and building your interfaces. You will learn how to work the accelerometer and create custom events. Then, you will understand how to use the basics, buttons, labels and text inputs and manipulate the widget tree. Next, you will be able to work with manipulating instructions, create an atlas and layouts. Moving on, you will learn packing for Windows and packing for iOS, and use TestDrive.

By the end of the book, you will have learnt in detail the relevant features and tools in Kivy and how to create portable packages to distribute your apps in the most used platforms.

Publication date:
August 2015
Publisher
Packt
Pages
246
ISBN
9781783987382

 

Chapter 1. Kivy and the Kv Language

In this first chapter, we will cover the following recipes:

  • Installing Kivy

  • Building your interfaces

  • Declaring properties within a class

  • Relating the Python code and the Kv language

  • Referencing widgets

  • Accessing widgets defined inside the Kv language in your Python code

  • Reusing styles in multiple widgets

  • Designing with the Kv language

  • Running your code

  • Using Kivy garden

 

Introduction


The first chapter is going to introduce the reader to the Kivy framework, its basis, and the Kv language. This is necessary work and a common base for the next chapters. If this is your first time using Kivy, it is advised that you do not skip this chapter. However, if you do, remember to return to this chapter if you need to install a supporting tool or verify any concept that you need to support your current solution.

 

Installing Kivy


This recipe will teach you how to install Kivy on a personal computer, which is the first step in starting to develop great software.

Getting ready

We will assume that you already have GNU/Linux (preferably Ubuntu/Debian/Trisquel, we recommend the last one) and Python installed on it. Usually, Python is already installed on the aforementioned GNU/Linux distributions. We will also assume that you are using Python version 2.7 or higher.

How to do it…

  1. Add one of the Personal Package Archives (PPAs) that you prefer; our recommendation is the following stable one:

    stable builds:  $ sudo add-apt-repository ppa:kivy- team/kivy
    nightly builds: $ sudo add-apt-repository ppa:kivy- team/kivy-daily
    
  2. Update your package list using your package manager:

      $ sudo apt-get update
    
  3. Install Python-kivy and, optionally, the examples that are found in Python-kivy-examples:

      $ sudo apt-get install Python-kivy
    
  4. Verify the installation. Call Python from the console and execute this command:

      import kivy

How it works…

There are many ways to get Kivy installed on your computer. Here we are describing probably the easiest way using your distribution's package manager. In the first step, we are adding a PPA as an APT repository to provide you with two different options: the stable one, for which all the Kivy products have been well tested, and the nightly one, which are packages under active development. Actually, for Ubuntu, you can skip the first step; it was just to get the latest version of Kivy.

In the second step, we update the list of available packages to include the Kivy repository. The third step is where the installation of Kivy really happens by using the distribution's package manager. In the last step, we verify if Kivy is working with the command that imports Kivy. If everything is OK we will see the following:

[INFO  ] Kivy v1.9.0

It shows the Kivy version that you installed in your system, which is v1.9.0 in this case. Remember to exit Python, for which we use the command quit().

There's more…

Now we will say something about Mac OS X and Microsoft Windows; for them, Kivy provides what is called portable packages. For an easy way to get Kivy running, just go to http://kivy.org/#download.

Mac OS X

Download the dmg file, double-click to open it, and drag the Kivy.app into your Applications folder. Ready!

You should run the make-symlinks script to make Kivy available in the shell system. Thus, you can run Kivy from the terminal.

Microsoft Windows

Download the .zip file and unzip it. There is a file named kivy.bat that must be copied as a shortcut into your SendTo folder.

See also

Well, if you are using a different operating system, you are always able to go to http://kivy.org/#download and look for the one that you are using. Also, if you want to build Kivy from the source code, refer to Chapter 8, Packaging our Apps for PC the recipe Packing for Linux.

 

Building your interfaces


Now we are going to create an interface, a very simple one, providing some basics in the developing of Kivy interfaces.

Getting ready

We are going to start to develop our first application with Kivy, and we need an editor for coding; you can use your favorite for Python without any problem. Here, we are using gedit, just because it comes with almost all GNU/Linux distros.

How to do it…

These steps will generate our first Kivy interface:

  1. Open a new file in gedit and save it as e1.py.

  2. Import the Kivy framework.

  3. Subclass the App class.

  4. Implement its build() method, so it returns a widget instance (the root of your widget tree).

  5. Instantiate this class and call its run() method.

The code for this is as follows:

import kivy
kivy.require('1.9.0') # Kivy ver where the code has been tested!

from kivy.app import App
from kivy.uix.label import Label

class MyApp(App):
    def build(self): 
        return Label(text='Hello world') 

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

How it works…

Well, let's see the code in detail; the first line is:

import kivy

This does the magic of linking Python with Kivy. The second line is optional:

kivy.require('1.9.0')

However, it is extremely useful because it prevents version conflicts; if you have an old Kivy version, you will have to update to at least the version that is required. In the third line:

from kivy.app import App

It is required that the base class of your app inherits from the App class, which is present in the kivy_installation_dir/kivy/app.py folder. This is to connect your app with the Kivy GUI. The fourth line is:

from kivy.uix.label import Label

The uix module is the section that holds the user interface elements, such as layouts and widgets. This is a very common import that you will use in the future. Moving on to the fifth line:

class MyApp(App):

This is where we define the base class of our Kivy app. You should only ever need to change the name of your app MyApp in this line. The sixth line is:

def build(self):

This is the function where you should initialize and return your root widget. This is what we do on the seventh line:

return Label(text='Hello world')

Here we initialize a Label with the text Hello World and return its instance. This label is the root widget of this app.

Now, on to the portion that makes our app come to life is in the eighth and ninth lines:

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

Here, the class MyApp is initialized, and its run() method is called. This initializes and starts our Kivy app.

There's more…

Something to point out is the name of the window, it will be called My because of the name of the base class. Ergo, if you want the title of the window be Win1, your base class must be Win1App. So, the fifth line would be:

class Win1App(App):

You must change the last one to:

Win1App().run()

Actually, a suffix of App isn't necessary; it is just commonly used in Kivy. If you want to include an App suffix in the title or spaces, override the title attribute as:

class Win1App(App):
    def build(self): 
        self.title = 'Win 1 App'

See also

If you want to run your interface, take a look at our recipe Running your code. Also you can take a look in the file kivy_installation_dir/kivy/app.py, which is a very good document to go deeper into Kivy apps.

 

Declaring properties within a class


Here we want to highlight an important difference between traditional Python coding and Kivy, and the usefulness of this change.

Getting ready

We need to remember the traditional form to declare properties in Python. Usually, if we want to declare a property in Python, we do something such as:

class MyClass(object):
    def __init__(self):
        super(MyClass,self).__init__()
        self._numeric_var = 1
@property
    def numeric_var(self): 
        return self._numeric_var

We are declaring a numeric one, whereas if we use MyClass().numeric_var in the Python shell, we get 1 in return.

How to do it…

Now, to declare this property in Kivy we follow these steps:

  1. Import Kivy and its properties

  2. Define the class

  3. Reference the Kivy property, in this case the numeric one:

    import kivy
    
    from kivy.event import EventDispatcher
    from kivy.properties import *
    
    class MyClass(EventDispatcher):
        numeric_var = NumericProperty(1.0)

How it works…

The idea behind this is that you inherit the declaration from Kivy's properties, which reduces the number of code lines.

To use them, you have to declare them at a class level. That is, directly in the class, not in any method for the class. A property is a class attribute that will automatically create instance attributes. Each property, by default, provides an on_<propertyname> event that is called whenever the property's state/value changes.

Something additional to point out is that NumericProperty accepts all the Python numeric values: ints, floats, and longs.

In general, Kivy properties can be overridden easily when creating the instance of the class, using keyword arguments such as ClassName(property=newvalue).

There's more…

They help you to:

  • Easily manipulate widgets defined in the Kv language

  • Automatically observe any changes

  • Check and validate values

  • Optimize memory management

Kivy provides more properties as follows:

  • NumericProperty

  • StringProperty

  • ListProperty

  • ObjectProperty

  • BooleanProperty

  • BoundedNumericProperty

  • OptionProperty

  • ReferenceListProperty

  • AliasProperty

  • DictProperty

See also

These properties actually implement the Observer pattern; if you want to learn more about patterns, you can find information online at http://www.oodesign.com/observer-pattern.html.

 

Relating Python code and the Kv language


This recipe will teach you how to relate the Kv language to Python code. Kivy provides a design language specifically geared toward easy and scalable GUI design. The Kv language separates the interface design from the application logic, adhering to the separation of concerns principle, where the application remains in Python and the design remains in the Kv language.

Getting ready

This recipe will create the same interface as the recipe Building your interfaces, but now using the Kv language; hence, it could be educational to look the code in there to make some comparisons. Again we are using gedit, just because it comes with almost all GNU/Linux distros.

How to do it…

These steps will generate our Kivy interface using the Kv language:

  1. Open a new file in gedit and save it as e4.py.

  2. Make a rule for the label.

  3. Provide the text for the label:

    <Label>:
        text: 'Hello World' 
  4. Open a new file in gedit and save it as e4.py.

  5. Import the Kivy framework.

  6. Provide a subclass to the App class.

  7. Implement its build() method, so it returns a widget instance.

  8. Instantiate this class and call its run() method:

    import kivy
    kivy.require('1.9.0') # Kivy ver where the code has been tested!
    from kivy.app import App
    from kivy.uix.label import Label
    class e4App(App):
        def build(self): 
            return Label() 
    
    if __name__ == '__main__':
        e4App().run() 

How it works…

Well, let's see the code in detail. The first line for the file e4.kv is:

<Label>:

This line creates the rule for a Label. The second one is:

text: 'Hello World'

In this, we define the text property for the Label with the value 'Hello World'.

Now, the first four lines of the Python file are the common ones to use Kivy in Python, and we already reviewed them in this chapter recipe Building your Interfaces. Moving on to the fifth line:

class e4App(App):

This is where we define the base class of our Kivy app. You should only ever need to change the name of your app e4App in this line, and here is where the relationship between the Kv language and the Python code occurs. What happens is that Kivy looks for a file named e4.kv, which could be present or not. The sixth line is:

def build(self):

This is the function where you initialize and return your root widget. This is what we do on the seventh line:

return Label()

Here we initialize a Label and returned its instance. This Label is the root widget of this app, and it must be the same in the KV file.

Now, on to the portion that makes our app come to life is in the eighth and ninth lines:

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

Here, the class e4App is initialized, and its run() method is called. This initializes and starts our Kivy app.

There's more…

The filename of the KV file should be such that adding the name of the KV file and App will become the name of the subclass of the App class. For example, if you change the name to Win1App, then you should also change the KV filename to Win1.kv.

Something to point out is that we can incorporate the KV code inside the Python file with the class Builder. We just add a few lines between the fourth and fifth lines in the Python code to import the Builder package and the override of the method as follows:

from kivy.lang import Builder
Builder.load_string('''
    <Label>: 
        text: 'Hello World' 
''')

See also

If you want to run your interface, take a look at our recipe Running your Code and compare the result with the recipe Building your Interfaces.

 

Referencing widgets


Sometimes, it is necessary to access or reference other widgets in a specific widget tree. In the Kv language, there is a way to do it using IDs.

Getting ready

This recipe will use two common widgets just for reference. The Button and TextInput fields are very common widgets.

How to do it…

This recipe is as follows:

  1. Make a rule

  2. Establish the ID

  3. Call the ID:

    <MyWidget>:
        Button: 
            id: f_but 
        TextInput: 
            text: f_but.state 

How it works…

Let's see the code; this is the first line:

<MyWidget>:

This is the name of the widget we will use, which is a clickable text input. The second line is:

Button:

This defines the button. The third line is:

id: f_but

This gives the button an ID of f_but, which we will use to reference the button. The fourth line is:

TextInput:

This defines the text input. The fifth line is:

text: f_but.state

This is the definition of the text that is in the text input where we are referencing the state of the button. It says that if you do not click the button, the text in the text input is normal, and if you click the button, the text in the text input is shown.

There's more…

An ID is limited in scope to the rule it is declared in, so in the preceding code, f_but cannot be accessed outside the <MyWidget> rule; that is, if we have a second <MyWidget2>, we are not able to reference f_but in <MyWidget2>.

Also ID is a weakref module for the widget and not the widget itself. As a consequence, storing the ID is not sufficient to keep the widget from being garbage collected. To demonstrate:

<MyWidget>:
    label_widget: label_widget.__self__ 
    Button: 
        text: 'Add Button' 
        on_press: root.add_widget(label_widget) 
    Button: 
        text: 'Remove Button' 
        on_press: root.remove_widget(label_widget) 
    Label: 
        id: label_widget 
        text: 'widget'

If we do not use ID.__self__ or in this case label_widget.__self__ just label_widget, we are going to get an error: ReferenceError: weakly-referenced object no longer exists.

See also

If you want to get more details about widgets, see the recipes in Chapter 4, Widgets.

 

Accessing widgets defined inside the Kv language in your Python code


This recipe will teach you how to access definitions inside the Kv language in your Python code and vice versa.

Getting ready

This recipe will use button, a very common widget that we also used in the last recipe.

How to do it…

This recipe follows as:

  1. Make a rule for the widget.

  2. Define a button.

  3. Give it an ID.

  4. Define the label for the button.

  5. In the action, call a method in the Python code:

    <MyW>:
        Button:
            id: b1
            text: 'Press to smash'
            on_release: root.b_smash()
  6. Create the Python code with the method:

    import kivy
    kivy.require('1.8.0') # replace with your current kivy version !
    
    from kivy.app import App
    from kivy.uix.widget import Widget
    
    class MyW(Widget):
        def b_smash(self):
            self.ids.b1.text = 'Pudding'
    
    class e7App(App):
        def build(self):
            return MyW()
    
    if __name__ == '__main__':
        e7App().run()

How it works…

In the Kv Language file, we have the following in the first line:

<MyW>:

This is the name of the widget, a simple button. The second line is:

Button:

This is the button definition. The third line is:

id: b1

This gives the button an ID b1. The fourth line is:

    text: 'Press to smash'

This makes the initial text on the button 'Press to smash'. The fifth line is:

    on_release: root.b_smash()

The preceding line is making a call to the Python code; it refers the method b_smash() of the root class MyW.

The fifth line in the Python code is:

class MyW(Widget):

This is the definition of the class related to the Widget. The sixth line is:

def b_smash(self):

This defines the method b_smash(), which is accessed by the Kv language file. The seventh line is:

self.ids.b1.text = 'Pudding'

This accesses the widget defined in the Kv language file, specifically the button with its ID, and changes the text displayed in the button to the text Pudding.

See also

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

 

Reusing styles in multiple widgets


This recipe will teach you how to take advantage of reusing styles for different widgets, a procedure that could be useful for the scalability of a system.

Getting ready

We will use this example of a file, e8.kv, where two widgets are defined:

<MyWidget1>:
    Button: 
        on_press: self.text(txt_inpt.text) 
    TextInput: 
        id: txt_inpt 
<MyWidget2>: 
    Button: 
        on_press: self.text(txt_inpt.text) 
    TextInput: 
        id: txt_inpt

We must note that they are very similar, and actually just the name of the widget is different between them.

How to do it…

The following steps provide a way to join the two widgets:

  • Let's conserve just one of the widgets.

  • The name of the discarded widget will be added to name of the conserved widget, by separating with a comma:

    <MyWidget1,MyWidget2>:
        Button: 
            on_press: self.text(txt_inpt.text) 
        TextInput: 
            id: txt_inpt 

How it works…

In this case, by separating the class names with a comma, all the classes listed in the declaration will have the same KV properties and you could join any number of similar widgets.

There's more…

In the Python code, the widgets could do different tasks, as in the next portion of code:

class MyWidget1(Widget):
    def text(self, val):
        print('text input text is: {txt}'.format(txt=val)) 
class MyWidget2(Widget): 
    writing = StringProperty('') 
    def text(self, val): self.writing = val 

Similarly, you can join the widgets in the Kv language.

See also

If you want to get more details about widgets, see the recipes in Chapter 4, Widgets.

 

Designing with the Kv language


This recipe will give you a first look at the widgets' distribution and their interaction.

Getting ready

This recipe will use two common widgets, just for reference; again we'll be looking at the Button and TextInput fields. Also, a common kind of layout is BoxLayout, which controls the distribution of objects in the interface.

How to do it…

This recipe works by performing the following steps:

  1. First, the KV file:

    <Controller>:
        label_wid: my_custom_label
    
        BoxLayout:
            orientation: 'horizontal'
            padding: 20
    
            Button:
                text: 'My controller info is: ' + root.info
                on_press: root.do_action()
    
        Label:
          id: my_custom_label
          text: 'My label before button press'
  2. Next, the Python code:

    import kivy
    kivy.require('1.8.0')
    
    from kivy.uix.floatlayout import FloatLayout
    from kivy.app import App
    from kivy.properties import ObjectProperty, StringProperty
    
    class Controller(FloatLayout):
    
        label_wid = ObjectProperty()
        info = StringProperty()
    
        def do_action(self):
            self.label_wid.text = 'Button pressed'
            self.info = 'Bye'
    
    class e8App(App):
        def build(self):
            return Controller(info='Hello world')
    if __name__ == '__main__':
        e8App().run()

How it works…

If we are designing with the Kv language, let's see it in detail. In the first line:

<Controller>:

We are given the rule Controller, so remember that you are going to need a class Controller in your Python code. The second line is:

label_wid: my_custom_label

This code line gives defines the label for this rule from a reference to the Label. The third line is:

BoxLayout:

We start the definition of the properties for the layout. In the fourth and fifth lines:

    orientation: 'horizontal'
    padding: 20

We give values to the properties: in this case, horizontal to the orientation and 20 to the padding (the empty space beyond the border of the window). The sixth, seventh, and eighth lines are:

Button:
    text: 'My controller info is: ' + root.info
    on_press: root.do_action()

This is the definition for the button. Here is the most important part of the designing with the Kv language: the order in which it appears in the code is the same as that in which the widgets are arranged in the layout, so the button will be the leftmost of all the widgets that we will use. The final part of the code is the definition of the Label:

Label:
    id: my_custom_label
    text: 'My label before button press'

There's more…

An interesting modification can be done to the following fourth line of the KV file:

orientation: 'horizontal'

To change the orientation of BoxLayout from horizontal to vertical, we can change the preceding line to the following line:

orientation: 'vertical'

It will have the same functionality, but the button will be above the label.

See also

If you want more details about widgets and layouts, see the recipes in Chapter 4 , Widgets.

 

Running your code


In this recipe, we want to teach you how to run the code that we have constructed using the Kivy framework.

Getting ready

This recipe needs some code to be run and Kivy to be properly installed. We will use the code in the recipe Relating Python code and the Kv language, where we have two files, e4.kv and e4.py.

How to do it…

This recipe may seem easy because it is just a few steps, but the explanation is important. Use Python from the shell to run the file e4.py:

$ Python e4.py --size=250x200

It will display:

How it works…

As we've already seen in the recipe Relating Python code and the Kv language, the call to the e4.kv file occurs inside the e4.py code; as such, Kivy does not need an explicit reference. We used the option size previously because Kivy has a default size (usually 800x600 pixels) that did not meet our expectations.

There's more…

Well, if you are using a different operative system, there are some other considerations.

Mac OS X

With Mac OS X we use a portable package and we need to run the file a little bit differently:

$ kivy e4.py --size=250x200

This is because the Kivy framework has been packed with Python in the program call kivy.

Microsoft Windows

In Microsoft Windows, the portable package is called with a secondary click, using Send to menu, and selecting Kivy.

See also

If you are interested in how to run your code on a mobile device, go to Chapter 9, Kivy for Mobile Devices.

 

Using Kivy garden


This recipe will teach you how to use Kivy garden, which is a helpful tool to get some Kivy add-ons.

Getting ready

This recipe needs the pip system, which is a package management system used to install and manage software packages written in Python. The installation is very easy: just go to https://pip.pypa.io/en/latest/installing.html and download get-pip.py. Now, in the terminal, type:

$ Python get-pip.py

This line installs pip.

How to do it…

These are the most important tasks with Kivy garden:

  1. Install Kivy garden:

    $ sudo pip install kivy-garden
    
  2. Install a garden package:

    $ garden install graph
    
  3. Upgrade a garden package:

    $ garden install --upgrade graph
    
  4. Uninstall a garden package:

    $ garden uninstall graph
    
  5. List all the garden packages installed:

    $ garden list
    

There's more…

Also, we want to be able to search in the Kivy garden; for example, we can:

  1. Search new packages:

    $ garden search
    
  2. Search all the packages that contain graph:

    $ garden search graph
    
  3. Show the following:

    $ garden --help
    

    All the garden packages are installed by default in ~/.kivy/garden.

Packing

If you want to include garden packages in your application, you can add the app to the install command. This will create a libs/garden directory in your current directory, which will be used by Kivy garden.

For example in my app, it is in the directory MyApp:

$ cd myapp
$ garden install --app graph

About the Author

  • Hugo Solis

    Hugo Solis is an assistant professor in the physics department at the University of Costa Rica. In the same institution, he collaborates with CITIC and CICIMA. His current research interests include computational cosmology, complexity, and the infl uence of hydrogen on material properties. He has wide experience in languages, including C/C++ and Python for scientifi c programming and visualization. He is a member of the Free Software Foundation and has contributed code to some free software projects. He has also been a technical reviewer for Mastering Object-oriented Python, Kivy: Interactive Applications in Python, and Learning Object-Oriented Programming by Packt Publishing. Currently, he is in charge of the IFT, a Costa Rican scientifi c nonprofi t organization for the multidisciplinary practice of physics (http://iftucr.org).

    Browse publications by this author

Latest Reviews

(5 reviews total)
Great book. Well explained. We need the 2nd edition!
I got what I needed. Perfect.
Excellent
Kivy Cookbook
Unlock this book and the full library for FREE
Start free trial