Kivy Tutorial Build Desktop GUI Apps Using Python
Kivy Tutorial Build Desktop GUI Apps Using Python
likegeeks.com/kivy-tutorial
Kivy is an open-source Python library; you can use it to create applications on Windows,
Linux, macOS, Android, and iOS.
We will discuss 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.
Installation
If you have multiple versions of Python installed on your computer, then you will have to
install Kivy in the version that you wish to use for development.
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.
1/23
2. Now we have to install the dependencies. Execute the following commands:
Then:
2/23
3. After installing dependencies for Kivy, install Kivy using the following command:
3/23
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.
To create a Kivy interface, we first need to import the Kivy app module in our program using
the following statement:
4/23
Now is the time to write our main program.
class FirstKivy(App):
def build(self):
return Label(text="Hello Kivy!")
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 the 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()
5/23
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 its size & position.
In the last program, we used the label. To create a button, import button instead of a label as
follows:
The button fills the window, don’t worry, we will resize it later.
The default color of a Kivy button is grey. You can change the color by specifying the
background_color property in the format (r, g, b, a). The code demonstrated below:
6/23
from kivy.app import App
from kivy.uix.button import Button
class KivyButton(App):
def build(self):
return Button(text="Welcome to LikeGeeks!", background_color=(155,0,51,53))
KivyButton().run()
When you run the program, it will show the button like this:
mybtn.disabled = True
7/23
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 two custom methods. The first method is the disable()
method. 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.
8/23
from kivy.app import App
from kivy.uix.button import Button
class KivyButton(App):
def build(self):
return Button(text="Welcome to LikeGeeks!", pos=(300,350), size_hint = (.25,
.18))
KivyButton().run()
The pos parameter specifies the position for the button while the size_hint parameter
specifies the size of the button.
In this section, you will learn to add an image to 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, several layouts can be used to organize the widgets, for example,
box layout, anchor layout, float layout, etc.
9/23
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.
Builder.load_string("""
<KivyButton>:
Button:
text: "Hello Button!"
size_hint: .12, .12
Image:
source: 'images.jpg'
center_x: self.parent.center_x
center_y: self.parent.center_y
""")
10/23
Similarly, you can load the Kv string from a separate file using the load_file method like this:
Builder.load_file("myfile.kv")
Kivy Label
In our first GUI app, we added a label to our form, but this time, we will play with the label
properties.
You can use a label to add text to our GUI. Kivy label supports ASCII and Unicode strings
only.
11/23
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:
Where the
[color][/color]
Kivy RecycleView
Assume that you have a great number of widgets that you want to display on your screen,
which may affect the performance.
12/23
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:
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:
Builder.load_string('''
<ExampleRV>:
viewclass: 'Button'
RecycleBoxLayout:
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
''')
class ExampleRV(RecycleView):
def __init__(self, **kwargs):
super(ExampleRV, self).__init__(**kwargs)
self.data = [{'text': str(x)} for x in range(20)]
Here
__init__
The constructor of the class with **kwargs meaning any arbitrary number of arguments or
keyword arguments are acceptable. Now calling the above class:
class RecycleApp(App):
def build(self):
return ExampleRV()
RecycleApp().run()
13/23
So the complete code will be like this:
class ExampleRV(RecycleView):
def __init__(self, **kwargs):
super(ExampleRV, self).__init__(**kwargs)
self.data = [{'text': str(x)} for x in range(20)]
class RecycleApp(App):
def build(self):
return ExampleRV()
RecycleApp().run()
Kivy ScrollView
14/23
The ScrollView in Kivy provides a scrollable view. Using scrollview, we can scroll through the
x-axis as well as the y-axis on the screen.
First, we will import a new function called runTouchApp(). This function will make our
scrollview touch-enabled.
runTouchApp(root)
15/23
Kivy Clear text input
In this section, we will create a text field and a button to clear the text field content.
After the input field, we have to create a button that clears our text.
For this, we will create a clearText method that 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.
16/23
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:
self.box.add_widget(self.txt)
self.box.add_widget(self.btn)
17/23
Kivy Clock
You can use the Kivy clock object to schedule a function call after specific intervals.
In this section, we will create a button. We will change the text of the button every 2 seconds
as an example for using Kivy clock.
class ClockExample(App):
i = 0
Now, create a button and using clock.schedule_interval we will call a user-defined function
every 2 seconds. Each time the function is called, the value of the counter variable is
incremented by one which is printed on the button.
18/23
def build(self):
self.mybtn = Button(text='Number of Calls')
Clock.schedule_interval(self.Clock_Callback, 2)
return self.mybtn
def Clock_Callback(self, dt):
self.i = self.i+1
self.mybtn.text = "Call = %d"%self.i
The dt argument is used to elapse time between the scheduling and the calling of the
callback function. If no argument passed, it would throw an error about the callback function
that it takes one positional argument, but two were given.
19/23
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 kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
20/23
kvWidget = """
MyWidget:
orientation: 'vertical'
canvas:
Color:
rgb: (255, 0, 0)
Rectangle:
size: self.size
pos: self.pos
"""
class MyWidget(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
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.
21/23
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.
22/23
Kivy vs. PyQt
Like Kivy, we also use PyQt to create GUI applications, but PyQt more popular in developing
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.
23/23