Unlock the Power of Mobile Development with Python and Kivy
Getting Started with Kivy
To begin, you’ll need a new directory for your app and Python installed on your machine. Open a new Python file and install the Kivy module from your terminal using one of the commands below. Make sure to install Kivy in a virtual environment to avoid package conflicts.
pip install kivy
# or
python -m pip install kivy
Creating the RandomNumber Class
Next, create a class that will define your app. In this example, we’ll name it RandomNumber
. This class will inherit the App
class from Kivy.
from kivy.app import App
class RandomNumber(App):
pass
In the RandomNumber
class, add a function called build
, which takes a self
parameter. This function will return the UI. For now, we’ll return a simple label.
from kivy.uix.label import Label
class RandomNumber(App):
def build(self):
return Label()
Outsourcing the Interface
Now, let’s outsource the interface. Create a Kivy file in your directory that will house most of your design work. Name this file the same as your class using lowercase letters and a .kv
extension.
Applying the Box Layout
To keep things simple, we’ll use the box layout. This layout arranges widgets and other elements in one of two orientations: vertical or horizontal.
# randomnumber.kv
BoxLayout:
orientation: 'ertical'
Label:
text: 'RandomNumber'
Label:
id: random_number_label
text: '_'
Button:
text: 'Generate'
on_press: root.generate_number()
Kivy color values are not your typical RGB values. They are normalized to avoid issues with illumination. To convert your normal RGB values to Kivy’s convention, divide all your values by 255.
Building the Rest of the UI
In the main.py
file, import the BoxLayout
and edit your main.py
file to return BoxLayout()
in the build
method.
from kivy.uix.boxlayout import BoxLayout
class RandomNumber(App):
def build(self):
return BoxLayout()
Generating the Random Number Function
Now that our app is almost done, let’s create a simple function to generate random numbers when a user clicks the Generate button.
import random
class RandomNumber(App):
def generate_number(self):
random_number = random.randint(0, 2000)
self.root.ids.random_number_label.text = str(random_number)
Manually Testing the App
The only thing left to do is make sure that you call this function when the Generate button is clicked.
Compiling Our App for Android, Windows, and iOS
Before compiling our app for Android, note that you’ll need Linux or macOS to compile your Android application. However, you don’t need a separate Linux distribution – instead, you can use a virtual machine. To compile and generate a full Android .apk
application, we’ll use a tool called Buildozer.
After following these steps, you should have a simple random number generator app on your phone. Congratulations! You’ve successfully created a mobile application with Python and Kivy.