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
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.
This recipe will teach you how to install Kivy on a personal computer, which is the first step in starting to develop great software.
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.
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
Update your package list using your package manager:
$ sudo apt-get update
Install Python-kivy and, optionally, the examples that are found in Python-kivy-examples:
$ sudo apt-get install Python-kivy
Verify the installation. Call Python from the console and execute this command:
import kivy
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()
.
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.

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.
Now we are going to create an interface, a very simple one, providing some basics in the developing of Kivy interfaces.
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.
These steps will generate our first Kivy interface:
Open a new file in gedit and save it as
e1.py
.Import the Kivy framework.
Subclass the
App
class.Implement its
build()
method, so it returns a widget instance (the root of your widget tree).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()
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.
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'
Here we want to highlight an important difference between traditional Python coding and Kivy, and the usefulness of this change.
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.
Now, to declare this property in Kivy we follow these steps:
Import Kivy and its properties
Define the class
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)
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)
.
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
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.
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.
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.
These steps will generate our Kivy interface using the Kv language:
Open a new file in gedit and save it as
e4.py
.Make a rule for the label.
Provide the text for the label:
<Label>: text: 'Hello World'
Open a new file in gedit and save it as
e4.py
.Import the Kivy framework.
Provide a subclass to the
App
class.Implement its
build()
method, so it returns a widget instance.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()
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.
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' ''')
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.
This recipe will use two common widgets just for reference. The Button
and TextInput
fields are very common widgets.
This recipe is as follows:
Make a rule
Establish the ID
Call the ID:
<MyWidget>: Button: id: f_but TextInput: text: f_but.state
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.
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.
If you want to get more details about widgets, see the recipes in Chapter 4, Widgets.
This recipe will teach you how to access definitions inside the Kv language in your Python code and vice versa.
This recipe will use button, a very common widget that we also used in the last recipe.
This recipe follows as:
Make a rule for the widget.
Define a button.
Give it an ID.
Define the label for the button.
In the action, call a method in the Python code:
<MyW>: Button: id: b1 text: 'Press to smash' on_release: root.b_smash()
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()
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
.
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.
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.
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.
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
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.
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.
If you want to get more details about widgets, see the recipes in Chapter 4, Widgets.
This recipe will give you a first look at the widgets' distribution and their interaction.
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.
This recipe works by performing the following steps:
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'
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()
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'
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.
If you want more details about widgets and layouts, see the recipes in Chapter 4 , Widgets.
In this recipe, we want to teach you how to run the code that we have constructed using the Kivy framework.
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
.
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:

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.
Well, if you are using a different operative system, there are some other considerations.
If you are interested in how to run your code on a mobile device, go to Chapter 9, Kivy for Mobile Devices.
This recipe will teach you how to use Kivy garden, which is a helpful tool to get some Kivy add-ons.
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
.
These are the most important tasks with Kivy garden:
Install Kivy garden:
$ sudo pip install kivy-garden
Install a garden package:
$ garden install graph
Upgrade a garden package:
$ garden install --upgrade graph
Uninstall a garden package:
$ garden uninstall graph
List all the garden packages installed:
$ garden list
Also, we want to be able to search in the Kivy garden; for example, we can:
Search new packages:
$ garden search
Search all the packages that contain graph:
$ garden search graph
Show the following:
$ garden --help
All the garden packages are installed by default in
~/.kivy/garden
.