Skip to main content

Kivy Python tutorial: Build attractive mobile apps in Python!

Python Kivy tutorial

In this Kivy Python tutorial, you will learn how to use Kivy for Python app development. By the end, you’ll understand how to start building cross-platform apps for Android, iOS, and Windows using Python.


Python is a powerful, flexible, and beginner-friendly programming language that has rapidly grown to become one of the most popular options for developers. But while Python is welcoming for newcomers and flexible enough for pros, getting the most from it will typically require a little help.

Also read: How to make a game in Python: An introduction to Pygame

That is to say, there isn’t a whole lot you can build with Python out-of-the-box. If you want to make a game, you’ll need the module Pygame. If you plan on making a website, you’ll need to use one of the popular Python frameworks, such as Flask.

But what if you want to make an Android app? In that case, you need Kivy!

Kivy is a Python library that supports cross-platform development. That means you can use a single code base to create Android, iOS, and even Windows, Linux, and MacOS apps. Kivy provides flexible, modern UI elements and, of course, let’s you keep using your new favorite language to build it all!

So, how do you get started? Let’s find out in this Kivy Python tutorial.

Kivy Python tutorial: Setting up

First need to download and install Kivy. Fortunately, you can do this via pip. So first, make sure that Python is installed on your machine. If it isn’t, you can fix that by following our helpful guide:

·         How to install Python and start coding on Windows, Mac, or Linux

Next, you’ll need to open up a command prompt in your Python folder, or add Python to PATH, if you’re on Windows. Or you can use the terminal.

Next, head on over to the instructions provided at Kivy.org. This will give you a detailed guide to getting things up and running.

The cliff notes version: ensure that you have the latest  pip, wheel, and virtualenv by running the following command at the Command Line:

python -m pip install --upgrade pip wheel setuptools virtualenv

Next, create a virtual environment for your Kivy project:

python -m virtualenv kivy_venv

kivy_venv\Scripts\activate

(Or source kivy_venv/Scripts/activate if in a bash terminal).

Install Kivy Itself

Credit: Adam Sinicki/ Android Authority

If this doesn’t work, try using “py” instead of “python.” Next, install the dependencies you need. These take up a little space, so if you want to be :

python -m pip install docutils pygments pypiwin32 kivy_deps.sdl2==0.1.* kivy_deps.glew==0.1.*

python -m pip install kivy_deps.gstreamer==0.1.*

python -m pip install kivy_deps.angle==0.1.* (If you have Python 3.5+)

Finally, install Kivy itself and the examples:

python -m pip install kivy==1.11.1

python -m pip install kivy_examples==1.11.1

Again, you can follow the instructions at Kivy.org for a more detailed guide.

Once you’ve done all of this, why not take a look at one of the examples?

python kivy_venv\share\kivy-examples\demo\showcase\main.py

Here, you’ll find a variety of different button layouts and be able to interact with them; an insight into the kinds of user interfaces you can create with Python app development via Kivy!

Kivy Example

Credit: Adam Sinicki/ Android Authority

Note that you’re going to need to create your virtual environment each time you begin development. So, don’t close that CMD window just yet!

Your first app

To get started, load your Kivy IDE/editor of choice. Again, you can find out how to do this in our previous post. I will be using Visual Studio.

Now enter the following code:

import kivy
kivy.require('1.9.0')

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

class HelloWorld(App):
    
    def build(self):
        return Label(text="Hello Wolrd")

helloWorld = HelloWorld()

helloWorld.run()

To run this, you will need to switch back to the terminal/command line, find the file, then launch it. I called mine Python_Kivy_Example.py.

If all has gone well, you’ll be greeted by the words “Hello World!” up on the screen:

Kivy Hello World

Credit: Adam Sinicki/ Android Authority

Remember: you need to be using the Kivy environment you set up in order for this to work. if you In this script, we are first importing Kivy and the individual elements that we need (an app and a label). Kivy.require() is what we use to target a minimum version of Kivy.

Next, we’re creating a class called HelloWorld, with function called build, which is going to return a label with the text “Hello World” (as is tradition).

Finally, we’re creating our Hello World object and then running it. Boom! There you have your first Kivy Python app! 

More things we can do

That was a very simple introductory project to show you how Kivy works for the purpose of this Kivy Python tutorial.

So, what else can this bad boy do?

One smart thing we can do with Kivy, is to separate the UI layer from the code — just as we do in Android Studio (where the UI is handled by XML in separate files). We would do this by creating separate Kivy files that could then display buttons and the like.

So, let’s create a new Kivy file and name it HelloWorld. In here, add the following code:

<label>:
        text: "Hello World"

Make sure this file is saved in the same folder as your Python file using the extension “.kv”, and then edit the original code slightly:

import kivy
kivy.require('1.9.0')

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

class HelloWorld(App):
    
    def build(self):
        return Label()

helloWorld = HelloWorld()

helloWorld.run()

You’ll notice that all we did was to remove the contents of the brackets following Label. It’s important that we give the class and the Kivy file the same name, as this is how Python knows to associate the two! Hit run, and you should find that everything looks just as it did before!

Now you can do things like changing the color and size of the label:

<label>:
        text: "Hello World"
        pos: 0, 100
        size: 100, 50
        color: .8,.9,0,1
        font_size: 32

Note that for this to work, you also need to import “color.”

from kivy.graphics import Color

If we want to stack multiple widgets in a single layout, we need to make a couple of small changes. Instead of returning a label, we’re going to return a layout. We’ll use box layout, which is one of the simplest options.

Kivy Box Layout

Credit: Adam Sinicki/ Android Authority

This will simply stack your widgets top to bottom, or left to right, depending on whether you set it to “verticle” or “horizontal.”

<BoxLayout>:
    orientation: 'vertical'
    Label:
        text: 'Label 1'
    Label:
        text: 'Label 2'
    Label:
        text: 'Label 3'

You can then display this using the following code:

import kivy
kivy.require('1.9.0')

from kivy.app import App
from kivy.uix.button import Label
from kivy.uix.boxlayout import BoxLayout

class HelloWorld(App):
    def build(self):
      return BoxLayout()

helloWorld = HelloWorld()
helloWorld.run()

Handling button presses

The next thing that any good Kivy Python tutorial needs, is a way to handle events and logic. If we want to swap those labels for buttons, we can do so very simply by importing “Button” instead of label and swapping every reference.

But we’re not going to do that. Instead, to keep things simple, we’re going to stick with just one button. This button will print “Hello World” to the CMD/terminal when clicked.

Your KV file will look like this:

<Controller>:
        BoxLayout: 
                orientation: 'vertical'

                Button:
                        text: 'Button 1'
                        on_press: root.button_pressed()

Here, we have added two new features of interest: the controller tag and the on_press. The controller tag is our “root widget.” All other widgets in the file are “children” of that root. The other point of interest is “on_press.” This calls a function that we’re adding to the code.

That code looks like this:

import kivy
kivy.require('1.9.0')

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout


class RootWidget(BoxLayout):
    def __init__(self):
        super(RootWidget, self).__init__()
        
    def button_pressed(self):
        print("Hello there")
    
class HelloWorld(App):

    def build(self):
        return RootWidget()


helloWorld = HelloWorld()

helloWorld.run()

As you can see, we are now returning “RootWidget” as our view. Meanwhile, RootWidget has its own class, which contains a little boilerplate code to initialize the view, along with the button_pressed function. This is where we

We can even take this Kivy Python tutorial one step further by showing you how to alter the layout from the code. To do this, we just need to create a label for one of our views, so that we can reference it later.

The new Kivy file:

import kivy
kivy.require('1.9.0')

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout


class RootWidget(BoxLayout):
    def __init__(self):
        super(RootWidget, self).__init__()
        
    def button_pressed(self):
        self.lbl.text = "Hello World!"

    
class HelloWorld(App):

    def build(self):
        return RootWidget()


helloWorld = HelloWorld()

helloWorld.run()

The new Python file:

<RootWidget>:
        lbl: my_label

        BoxLayout: 
                orientation: 'vertical'

                Button:
                        text: 'Button 1'
                        on_press: root.button_pressed()

                Label:
                        id: my_label
                        text: 'Waiting...'

Clicking the button will now display “Hello World!” on a label positioned directly underneath.

Kivy Button Press

Credit: Adam Sinicki/ Android Authority

There’s plenty more you can do but, hopefully, this Python Kivy tutorial has given you a good foundation to build off of. There are tons of resources and tutorials out there, so pick an easy project and give it a go!

Also read: How to define a function in Python

But wait! You’re probably wondering how you package all of this into an APK file? To do that, you’ll need to use another external tool called Buildozer. That’s an article for another time. But meanwhile, you can follow the documentation, here:


As you can see, there is a lot you can do with Python once you get to grips with it! If you want to go pro with this awesome language, then why not take an online course? You can find some incredible discounts on top Python courses and learn for as little as $40, here:



source https://www.androidauthority.com/kivy-python-tutorial-build-attractive-mobile-apps-in-python-1142003/

Comments

Popular posts from this blog

5 tips to Voice Speech Recognition in Android Marshmallow

Android Marshmallow landed on our Android devices. The opportunity for us to offer a small compilation of tricks to try immediately. The latest version of the Google OS starts (very gently, unhurriedly) to be offered on other devices as Nexus. You will find on Android TM, in the coming weeks, a compilation of the best tips for Android 6.0 Marshmallow. It starts slowly with a video featuring the 10 essential tips & tricks of this new version of the little green robot OS. To continue, we offer a selection of five "tricks" on the management of the battery on Android 6.0 Marshmallow. To enjoy longer your newly updated mobile. Follow the guide. then continue with 5 tips to tame the super-assistant Google Now on Tap. Here you will find 5 "tips" to manage in the best way your applications. We then discuss the quick tips to navigate more easily on this version of the Google OS. We enchanters with features focused on safety and the protection of personal data. We co...

Energy Android TV Play turns your TV into a Smart TV

ENERGY SISTEM Android Energy TV Play, you have a smart TV with Android operating system allows you to convert any traditional TV has announced the launch of a new product. Energy Android TV Play can be connected to the TV to enjoy f the size of a flash drive, a smart phone, a tablet and a computer unconsolidated is a lightweight device. System 1.6 GHz, DDR3 1GB of RAM and a dual-core processor can be expanded using external USB devices, which is the internal memory of 8 GB. It also integrates WiFi and a USB port for connecting external devices. One of its outstanding features, it is easily connected to the TV screen by screen cast application to display the contents of any terminal, making any phone or tablet is synchronized with iOS or Android. All ENERGY SISTEM products one click In addition, through streaming media service applications, images, video or other multimedia content, and game play is the ability to share. With integrated WiFi, the device you want from t...

How to run Python apps on any platform

Credit: Adam Sinicki / Android Authority Want to know how to run Python? It sounds simple, but it can actually be tricky to figure this out. In this post, we’ll discuss how to test your Python code, as well as how to run Python in other contexts: online for example, or as a packaged app. Sometimes, the thing holding you back from learning to code can be extremely simple. I remember wanting to learn to program when I was younger – or learning to take what I’d learned from BASIC on the ZX Spectrum and apply that to a modern environment. My problem? I didn’t know “where” to program. Once I understood C# or Java, where would I enter the code and how would I run it? And whenever I asked someone, they would look at me blankly. What kind of a question is that? Thing is, I had never needed an IDE or an interpreter before. Machines like the ZX Spectrum and Tatung Einstein (any other Einstein users out there?) simply booted up with a prompt to code into! Many people have a similar iss...