Python

Kivy tutorial – Build desktop GUI apps using Python

In previous tutorials, you saw how to build GUI applications using Tkinter and PyQt5, in this tutorial, we will continue building desktop GUI applications but this time using Kivy.

Kivy is an open source Python library which is used to create applications on Windows, Linux, MacOS, Android and iOS.


You will learn how to play with the Kivy buttons, labels, recycle view, scroll view, Kivy Canvas, and other widgets to become familiar with the library.

You can design Kivy widgets using an intermediate language called Kv language as you’ll see later.

Before getting started with Kivy, a basic knowledge of Python programming basics is needed. Now, let’s start from installation.

 

Installation

If you have multiple versions of Python installed in your computer, then you will have to install Kivy in the version that you wish to use for development.

Assuming Python to be installed, consider the following steps:

  1. The python packages can be installed using pip. As Kivy needs compilation when installing with pip, therefore, we need wheels which is a pre-built distribution of an already compiled package. You can also use git to install Kivy but in this tutorial, we will use wheel.

Run the following command to get pip and wheel installed:

python -m pip install --upgrade pip wheel setuptools

Kivy tutorial

  1. Now we have to install the dependencies. Execute the following commands:

python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew

Then:

python -m pip install kivy.deps.gstreamer

Install Kivy dependancy

  1. After installing dependencies for Kivy, install Kivy using the following command:

python m pip install kivy

Kivy installed

 

Kivy GUI

In this section, you will learn how to create and run a Kivy program and how to build a basic interface in Kivy.

Let’s create a file with .py extension.

To create a Kivy interface, we first need to import the Kivy app module in our program using the following statement:

from kivy.app import App

Now importing Label from kivy.uix.label:

from kivy.uix.label import Label

Now is the time to write our main program.

In the above snippet, a class is inherited from the App class. Then to build the application we have to return a widget on the build() function. In the code above, we have returned a label with text “Hello Kivy”.

The last step is to call this function. You can either create an object of the class or just write the following statement:

FirstKivy().run()

The entire python file looks like the following:

The result of this code will be like this:

Run first Kivy app

Congratulations! Your first Kivy app runs successfully.

 



Kivy Button

In this section, you will learn how to create a button, change the color of a button, enable/disable, how to add an image on the button and how to change the size & position of the button.

In the last program, we used the label. To create a button, import button instead of a label as follows:

The entire output screen will be as follows:

Add button to Kivy app

The button fills the window, don’t worry, we will resize it later.

Change color of Kivy button

The default color of a Kivy button is grey. The color can be changed by specifying the background_color property in the format (r, g, b, a). The code demonstrated below:

When you run the program, the following button is created:

Change Kivy button color

Disable Kivy Button

To disable a button, you have to set the disabled property to True.

Consider the following code to disable a button after it is pressed:

In the above code, we have imported partial function from the functools so that we can use the bind() function.

A KivyButton() class is created with 2 custom methods. The first method disable(). You can name it what you want

Then we have the update() method to update the text of our button after clicking on it. Also, you can name your function as you want.

The next function is the build() function. This method runs automatically when a button is created. Then we have called the disable() method using partial. Similarly, the update() method is called to update the text of the button after it is disabled.

The return value from the disable() function is bound to the on_press function of our button. Therefore, when the button is pressed, it is disabled first and then the text is updated.

The output is like this:

Disable Kivy button

Change the size and position

Using the pos and size_hint property of the button widget, you can easily change the position and size of a button respectively. You can change the size and the position of a Kivy button like this:

The following output will be like this:

Change Kivy button size & position

The pos parameter specifies the position for the button while the size_hint parameter specifies the size of the button.

Image in Kivy Button

In this section, you will learn to add an image on a button. We will be using Kv language for the first time to create our widgets instead of instantiating them from code.

Given below are the Kivy libraries that we are going to import:

BoxLayout is used to position the widgets so that widgets can be placed together in an organized manner. In Kivy, there are several layouts that can be used to organize the widgets, for example, box layout, anchor layout, float layout, etc.

Load Kv string or file

By default, Kivy tries to load the Kv file with the same name as your class but without the word App and in lower case.

If your class is TestApp, so it will search for a Kv file with name test.kv on the same directory to load widgets from it.

The other way to load the kv file using the Kivy Builder.

Kivy Builder is used to load widgets from Kv strings or files. For example, if you want to create a widget, you can use the builder like this:

Builder.load_string(""" """)

Inside the triple quotation marks, the required widgets are added along with their properties. In the example below, we have added a KivyButton class.

First, the text and size of the button are set, then the image is specified in the source attribute and the image coordinates.

The image is placed on the same directory, so the image path is fine now.

Now, let’s import this definition and run our class:

The generated output looks like this:

Add image to Kivy button

Similarly, you can load the Kv string from a separate file using the load_file method like this:

The file here contains all Kivy widgets definition.

 

Kivy Label

In our first GUI app, we added a label to our form, but this time, we will play with the label properties.

A label is used to add text to our GUI. ASCII and Unicode strings are supported by a Kivy label.

 

Change the font size

The font size of the label can also be changed using the font_size property:

Change label font size

Adding Style to text in Label

In this section, we will change the styles of the text in the label.

For example, bold, italic, change color, underline and much more using markup. Consider the following statement:

Label(text='[u][color=ff0066][b]Better days[/b][/color] are coming; They are called [i][color=ff9933]Saturday[/i] and [i]Sunday[/color][/i][/u]', markup = True)

Where the [u][/u]  for underline font, [b][/b]  for bold font, [i][/i]  for italic font, and [color][/color]  for colorizing the font.

This result will be like this:

Styling Kivy label

 


Kivy RecycleView

Assume that you have a great number of widgets to be displayed on your screen which may affect the performance.

The goal of RecycleView is to arrange the view groups on the screen.

RecycleView is memory efficient as it loads contents into memory according to the size of the screen, unlike ListView where all items are loaded into memory.

One of the key features of RecycleView is that it supports animation. RecycleView can create an interactive and efficient scrollable list.

Before start coding, there are two main concepts to focus on:

  1. View Holder which holds a view and helps the recycling.
  2. The adapter which is used to adapt the data to display in the list.

To use RecycleView, we need to import RecycleView from the recycleview module as follows:

from kivy.uix.recycleview import RecycleView

In the example below, we will create a vertical list of buttons. Therefore, the view items that we want to place are the buttons:

The first step is to define the layout and view class of our recycleview:

Now we have to define our recycleview class:

Here __init__  is the constructor of the class with **kwargs meaning any arbitrary number of arguments or keyword arguments are acceptable. Now calling the above class:

So the complete code will be like this:

And the output looks like this:

RecycleView example

 

Kivy ScrollView

The ScrollView in Kivy provides a scrollable view. Using scrollview, we can scroll through x axis as well as y axis on the screen.

First, we will import a new function called runTouchApp(). This function will make our scrollview touch enabled.

from kivy.base import runTouchApp

We will define the scrollView as follows:

The output will be like this:

Kivy ScrollView

 


Kivy Clear text input

In this section, we will create a text field and a button to clear the text field content.

For the text field, import the textinput module:

from kivy.uix.textinput import TextInput

Let’s create a BoxLayout to add our widgets inside our class.

self.box = BoxLayout(orientation='horizontal', spacing=20, pos=(0,550))

Now we are going to create an input field:

self.txt = TextInput(hint_text="Write here",size_hint=(.5,.1))

After the input field, we have to create a button which clears our text.

For this, we will create a clearText method which sets the text to an empty string and we will call this method when the button is pressed that is by using the on_press property of the button.

Therefore, when we press the button the text will be erased.

self.btn = Button(text='Clear All', on_press=self.clearText,size_hint=(.1,.1))

Now we have to add our widgets (input field and button) into the boxlayout:

The ClearText method looks like the following:

The entire code will be like this:

The output will be like this:

Clear Kivy text input

 

Kivy Clock

The Kivy clock object is used to schedule a function call after specific intervals.

In this section, we will create a button. The text of the button will be changed after every 2 seconds.

Import the following modules first:

Now, create a class and initialize a counter variable as follows:

Now, create a button and using clock.schedule_interval we will call a user-defined function after every 2 seconds. Each time the function is called the value of the counter variable is incremented by 1 which is printed on the button.

The dt argument is used to elapse time between the scheduling and the calling of the callback function. if no argument passed, it will throw an error about the callback function that it takes 1 positional argument but 2 were given.

The complete code looks like this:

Every 2 seconds, the button text will be changed as expected.

Kivy clock

 


Kivy Canvas

The graphical representation of a widget is represented by Kivy canvas. You can draw what you want inside a canvas.

In this section, you will learn to create a canvas and how to draw a rectangle on the canvas.

We are going to create a canvas in boxlayout and then a rectangle on the canvas.

Import the following modules:

Consider the code below to create a canvas:

In this code, we have a BoxLayout class named MyWidget. Now the kvWidget string defines a canvas with its color property and a rectangle with the same size and position of the BoxLayout.

The complete code will be like this:

The output will be like this:

Kivy canvas color

 

Canvas Image

To add an image to the canvas, we will create a rectangle equal to the size of the canvas and then will add an image on the rectangle.

The kvWidget string will look like the following:

The output will be like this:

Kivy canvas image

 

Kivy vs PyQt

Like Kivy, PyQt is also used to create GUI applications, but PyQt is best known for desktop applications.

Although we discussed Kivy here to build desktop applications, Kivy is commonly used for mobile applications due to Kivy widgets capabilities in multitouch.

PyQt library is available in other programming languages such as C++ while Kivy is only available in Python.

Kivy uses OpenGL interfaces to draw widgets directly on the screen, so you can also create games with good graphics.

 

I hope you find your suitable Python GUI framework to build what you need.

At last, we discussed many examples for Kivy and previously Tkinter, PyQt5. Which one do you prefer in building your graphical interfaces?

Ayesha Tariq
Ayesha Tariq is a full stack software engineer, web developer, and blockchain developer enthusiast. She has extensive knowledge of C/C++, Java, Kotlin, Python, and various others.

4 thoughts on “Kivy tutorial – Build desktop GUI apps using Python

  1. Awesome, in-depth tutorial. Nice work.

    I did find, however, on the kivy canvas portion, an error is generated if “super().__init__” is not replaced with “super( baseclass, self).__init__” for Python 2.7.

    Thanks Again!

    1. Thanks for your comment.
      The tutorial we used python 3.7. Regarding Python 2.7 I don’t know the behavior.

Leave a Reply

Your email address will not be published. Required fields are marked *