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

4 Surprising Ways Artificial Intelligence will Empower Consumers

Ever wonder what makes Siri search the items inside the iPhone and on the web by recognizing your voice? How does Google listening work? Artificial Intelligence and data science have already infused in this consumer-oriented generation, but we have not realized it yet. It has been quite a while that natural language processing, speech recognition, and gesture recognition system took over the market with their all new features, but what are the new things in AI that are yet to come? Few amazing transformations are: Retailing sector to become AI-ready Voice Recognition will change the game Search engines to become smarter Machine learning to bring revolutionary changes Recently we got to learn about a verbal spat between Elon Musk and Mark Zuckerberg over the probable risk and opportunities brought by AI . Believe it or not, but we already accustomed to Artificial Intelligence and probably waiting to witness jaw-dropping inventions. Some of AI inventions we have known till yet are: Mach

How to unhide or show folders in mx player list

In this blog post, I tell you about how to Show or Hide folders from MX player list. There are two methods to Show folder from MX Player list. Method 1: Unhide / show folders If you want to temporarily Show / Unhide hidden folder from MX Player list, then go to Settings and untick Recognize .nomedia ".  Method 2: Permanently unhide / show folder: Open memory by any file explorer and I recommend X-Plore, and open the folder that is Hidden and find the file " .nomedia ". If you didn't find it, you should first enable "Show files hidden files that starts with .(dot)". Delete the file and you just need to refresh MX Player list to take changes. Note: MX Player always hide those folders which file " .nomedia " exists.

How to use arrays in Python

Arrays in Python give you a huge amount of flexibility for storing, organizing, and accessing data. This is crucial, not least because of Python’s popularity for use in data science. But what precisely is an array? And how do you use arrays in Python? Also read: How to use dictionaries in Python Read on, and we’ll shed some light on the matter. What is an array? An array is a way to store multiple values in a single variable. That means that you can use a single “reference” in order to access your data. A list is also an example of a variable that stores multiple values, but has some slight differences. When using lists in Python, you store a series of values each with a numbered index. For example, this is how you would create a list of fruits in Python: fruits = [“apple”, “orange”, “pear”, “nectarine”] If we then say: print(fruits[3]) We will see “nectarine” appear on the screen (the first entry is stored as “0”). Also read: How to use lists in Python This is not an