Figure 1.1

Have you ever thought about how cool it would be to design your own game for a mobile device, tablet or pc? Or, maybe you even had the idea of how, if only, some multi-touch application existed, a certain thing would be a cinch to do, or make yet another a lot more convenient. We’ve all been on this same train of thought at some point or another in this learning to program journey. The gap has often been not knowing the resources to use or not having the general knowledge to bring our lofty ideas to fruition. Well, in the next twenty or so minutes (depending how fast you read and comprehend), we will spend time learning about a graphical framework for Python that will literally leave your mouth agape and mind befuddled, astonished at the creative potential of such a tool with minimum lines of code.

The tool in question is It runs on Windows, OS X, Linux, and Android (with or without the Android API). That’s right, I said Android. …easy mobile app development anybody?

By now, if you have any experience with Python, I’m sure you’re probably thinking: aren’t there other really good graphical Python frameworks: Tkinter, WxPython, Wax, IronPython, PyQt, and many others. You are right; there are …! But the icing on the cake with Kivy is that it allows multi-touch screen development for user interfaces using the Python language.

Not only can Python code be used to design Kivy applications, but Kivy has its own language, which allows for rapid prototyping of widget trees and bindings that would be verbose in the strictly-traditional Python language. You can compare Kivy in context to purpose and functionality to CSS. Kivy is to Python what CSS is to HTML. This may be an over generalization, but it drives the point home. Using the Kivy language also promotes the separation of code logic from User Interface, which is always a best practice to strive for….
Let’s take Kivy for a spin around the block. You will see that it does not take a road trip to see how good this baby handles.

I will be using a Windows machine. But, as mentioned, Kivy is cross-platform. So, you have several or more system options to choose from, depending on availability and your comfort level. I will be using the Python IDLE as my Python editor, and Note++ as my Kivy editor. Again, you have an array of options to choose from including: notepad, IDLE, PyCharm, etc. I’ve been using PyCharm for a few months, and really appreciate all of the intelligent features available. It’s a paid app, but can be used as a full-featured app for a 30-day trial period. However, I will stick with IDLE in this tutorial. You should ensure that you install Python (2.7 or 3.4) on your pc before installing Kivy or whatever IDE you choose. I will be using Python 2.7.11, but you are welcome to use whatever version you like 2.7.x up to 3.4, which can be downloaded here, depending on your O.S.: https://www.python.org/downloads/.

Kivy is also an open-source Python framework. As a result, it has wide and far-reaching support. In addition to this technical support, there are many developers who regularly contribute to the development of Kivy add-ons, making it even more extensible. There is a centralized repository where you can search for and obtain these add-ons called kivy-garden (https://github.com/kivy-garden and https://libraries.io/github/kivy-garden/repositories).

If you want to run your app on Android, you only need to get Kivy-Buildozer, and you are off and running with developing apps for your tablets and mobile devices (https://github.com/kivy/buildozer).

Here is a graphical representation of the Kivy architecture:

Figure 1.0

Figure 1.0: Kivy Language Architecture

Install/Configuration

Let’s download and install Kivy. Go to this site and select the software version that is compatible with your PC: https://kivy.org/#download.

It is important to notice that when selecting the download link, you are taken to installation instructions. The premise is that Python is already installed. OS X and Linux users only need to follow the installation steps. However, Windows users need to ensure that their installed Python app is in the environment variables file path.

The most straightforward waqy to do this is to go to Control Panel > System and Security > System > Advanced System Settings. Select the Advanced tab. Select the Environment Variables button. Go to the System variables window, scroll down and select Path. Now, select the “Edit” button. Go to the very end, and enter the path to your Python folder (pay attention to the syntax of other path variables and follow their lead. When finished, select okay and close the appropriate windows. Now, you can follow the instructions for installing Kivy.

Let’s get into the first example, just to ensure that our installation was successful and to see a basic Kivy screen. First, check the Kivy version by entering the following on the IDLE command line:

If Kivy installed correctly, this code will display the version of Kivy installed. In IDLE or whatever Python editor you are using, enter the following:

Figure 1.1

Figure 1.1: Importing the Kivy App

When you run this command, information is returned about the Python version, Kivy version, and the current OS. This also lets us know that our Kivy version was installed successfully and will run. Now, enter the following code on the command line or create a file and name it myKivy.py:

Kivy Examples

Kivy-Python Code: Displays Howdy screen

The first line imports our Kivy application class which is the base for designing our Kivy application. Line two imports a Button widget. We create a class name that uses the base class App to create our own app and with the def build function, we instantiate our class (returns a widget instance—top-level widget, unless overridden). We then return the Button widget as the base of our application (takes up the entire app screen), and gives it the name “Howdy”. Finally, we run our application with myKivy().run.

Figure 1.2

Figure 1.2: Kivy “Howdy” button is displayed

Thus far, we have only used the Button widget as the basis for our application. Widgets are the building blocks of creating user interfaces in Kivy. They provide a canvas that can be used to draw on screen, and they can receive events and respond to them.

Easy, smeasy … right. Yeah, the code is typical Python so far. Let’s look at a few more examples.

With your Python Editor create a file named scatter.py and enter the following code:

Kivy-Python code to show the Scatter widget

The code is very familiar to the example of our “Howdy” screen. However, we are adding more building blocks. Notice in the import module section (preprocessor directives), we are adding three widgets this time: Floatlayout, Label, and Scatter.

  • FloatLayout—allows us to supersede the graphical layout restraints that other widgets are bound by. Its children can be moved to almost any area of the screen.
  • Label—the label widget allows us to generate text to the screen.
  • Scatter—this widget is unique in the sense that it allows user interaction: drag, rotation, etc…

Note that there are three widgets that we created instances of, but we can only return one widget. Therefore, the other two widgets must be children of the base, top-level widget. We do this by using the add_widget method. We add our Scatter widget to our Float widget (top-level). We then add the Label widget to our Scatter widget. The children inherit the behavior of the parent. All widgets are below the float widget, so we return our float instance (f). We get the following application:

Figure 1.3

Figure 1.3: Using the Float, Scatter, and Label widget

We can now move the text around the screen by left-clicking on it and dragging it. It is important to remember that Kivy supports multi-touch. As a result, if you have a touch-screen laptop, you can simply touch the text and drag it. You can also notice the two red dots on the “w”. Right-click over any area around the text to create a dot (anchor point), and let go. Then right-click on another area, and let go. Now with your mouse or touch screen, you can rotate the text in different degrees, as well as zoom in and out. Pretty slick, right?

Clock/Stopwatch Application

We are going to build a 24-hour clock that includes a stopwatch to see more of the graphical characteristics of Kivy. Up until now, we have used just the Python programming language. However, we will now separate user interface from logic, and see what the Kivy language can offer us. Let’s start by showing what we want to achieve:

Figure 1.4

Figure 1.4: Create a Clock/Stop Watch with Kivy

As you can see, this is a basic graphical representation of a standard 24-hr clock and a stopwatch, with two control buttons. When you dive into Kivy, head first, at your leisure, you will discover just how complex you can get with the graphical design of this clock. We can adjust our button size, use led digital or round clock display, utilize multiple screens (separate the clock from the stop watch), add on other widget applications in a separate screen of the same app and add exquisite fonts and colors, and much more. If we were to do that here, it would generate code that would be, first, very difficult to read and comprehend, and second it would increase the length of this tutorial by having to explain the not so clear implementations inside the code. We, therefore, follow an old idiom that has always served me well when learning new things: kiss (keep it simple stupid). Over inundating oneself with information is one of the surest ways to create learning gaps; take chunks at a time … chunks at a time.

Python File

Figure 1.5

Figure 1.5: Python file 1 – Clock/Stopwatch logic

Figure 1.6

Figure 1.6: Python File 2 – Clock/Stopwatch logic

This is our Python code that contains the logic of our clock and stop watch. It’s only about 50 lines of code. Think about how much code would be included if we used the Pythonic way of implementing our user interface. I will not spend a great deal of time on the Python code, since this should be familiar if you are even having a glance a Kivy. But, let’s look at the overall structure. Notice the different modules that we are importing to make use of certain widget features. We import the base Kivy module and use it to require users to utilize, at least, the specified Kivy version to run our code. Kivy also has a Clock module that we are making use of because we are creating a clock and stopwatch that need to be updated at specified intervals. The ObjectProperty is used with binding events. You should also note the MyWidgetClass. It has a BoxLayout widget as a parameter. We then pass to the next class. That’s a quick way to instantiate a widget(s). This is because we can only return one widget in our def builder() function (the function that instantiates our application). This will become more apparent as we look at our Kivy file. When we create our .kv file, there is one of three requirements to follow before it will recognize your Python file:

  1. Name the .kv file the same name as the first part of your base class (not case sensitive). In our example above, this would look like: TestApp -> test.kv
    1. Import the Builder module with the following line: from kivy.lang import Builder

    2. Just above your first class do: Builder.load_file(‘path/to/file.kv’
    3. Or do: Builder.load_string(kv_string)

Either one of these methods may be used, but one definitely has to be implemented. The first one seems straightforward enough to me; that’s why I used it.

Kivy File

Now, we look at our Kivy file:

Figure 1.7

Figure 1.7: Kivy file 1 – Clock/Stopwatch UI

Figure 1.8

Figure 1.8: Kivy file 2 – Clock/Stopwatch UI

We immediately notice that our Kivy file is only approximately 50 lines of code. Another thing that you probably notice is the tree structure. It makes things easier to read and understand. You can quickly determine the parent(s) and their children, if any. Line 1 is more of a best practice moment (“The content of a .kv file should always start with the Kivy header and version”). Line three is our root widget (always the widget in <…>). However, Kivy can have more than one root widget. However, for our purposes, we didn’t need more than one. You should also notice that the “MyWidgetClass” from our Python file is declared as the root widget. It is a BoxLayout type widget. Therefore, we use 5 attribute properties just below it to give definition and meaning to it. Another thing to note is that all other widgets are children of the MyWidgetClass (root). Lines 4, 11, 24, and 29 are critical in executing events (id and name). This makes it easy to access these widgets, and their attributes, from other widgets or from our Python file. On line 5, I use a custom attribute name b_font_size (button font size). Notice that its location is at the root widget, so it can be used globally (within any of the children). In addition, “30 sp” denotes a unit measurement that will automatically grow and shrink as the main screen is resized. Lines 12 and 25 are interesting in that they show Kivy HTML like behavior by using markup. Those two lines are in Labels which are used to render text. Notice that we need to make markup available by setting the markup attribute to True. Below is a list of available markup from https://kivy.org:

Figure 1.9

Figure 1.9: Kivy Markup tags

In line 29 (Slider widget), we gave our widget an id. All of the attributes are set within the widget to determine the behavior we expect. We are able to use the feature that slider provides simply by using the id, which we do in line 26 to resize the text in our label (standard clock):

Figure 2.0

Figure 2.0 Kivy – Slider close to max size of clock

Figure 2.1

Figure 2.1 Kivy – Slider close to min size of clock

The last thing that I will mention are lines 45 and 52. These lines allow us to bind our button widgets to our event handlers. We bind the Start stop button to our start_stop() function in our Python file, and we bind our Reset button to our reset() function in our Python file. In these lines, we use app.func_name(). We use that because they refer to the instance of our application. Here is another guideline that is useful when using kivy that comes straight from https://kivy.org:

There are three keywords specific to Kv language:

  1. a) app: always refers to the instance of your application.
  2. b) root: refers to base widget/template in the current rule
  3. c) self: always refer to the current widget

That about sums it up this time around. Time flies when you’re having fun. I encourage you to copy the examples given above and experiment with adding/removing widgets and attributes to gain a rudimentary knowledge of development in Kivy. Playing around with the graphical features can be tricky, but the API and trial and error are your friends.

Create a folder on your desktop with two files inside: kv.py, and test.kv (you can use notepad or any file editor to create the Kivy file).

Leave a Reply

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