We are going to start to develop our first application with Kivy, and we need an editor for coding; you can use your favorite for Python without any problem. Here, we are using gedit, just because it comes with almost all GNU/Linux distros.
These steps will generate our first Kivy interface:
- Open a new file in gedit and save it as
e1.py
. - Import the Kivy framework.
- Subclass the
App
class. - Implement its
build()
method, so it returns a widget instance (the root of your widget tree). - Instantiate this class and call its
run()
method.
The code for this is as follows:
Well, let's see the code in detail; the first line is:
This does the magic of linking Python with Kivy. The second line is optional:
However, it is extremely useful because it prevents version conflicts; if you have an old Kivy version, you will have to update to at least the version that is required. In the third line:
It is required that the base class of your app inherits from the App
class, which is present in the kivy_installation_dir/kivy/app.py
folder. This is to connect your app with the Kivy GUI. The fourth line is:
The uix
module is the section that holds the user interface elements, such as layouts and widgets. This is a very common import that you will use in the future. Moving on to the fifth line:
This is where we define the base class of our Kivy app. You should only ever need to change the name of your app MyApp
in this line. The sixth line is:
This is the function where you should initialize and return your root widget. This is what we do on the seventh line:
Here we initialize a Label
with the text Hello World
and return its instance. This label is the root widget of this app.
Now, on to the portion that makes our app come to life is in the eighth and ninth lines:
Here, the class MyApp
is initialized, and its run()
method is called. This initializes and starts our Kivy app.
Something to point out is the name of the window, it will be called My
because of the name of the base class. Ergo, if you want the title of the window be Win1
, your base class must be Win1App
. So, the fifth line would be:
You must change the last one to:
Actually, a suffix of App
isn't necessary; it is just commonly used in Kivy. If you want to include an App
suffix in the title or spaces, override the title attribute as:
If you want to run your interface, take a look at our recipe Running your code. Also you can take a look in the file kivy_installation_dir/kivy/app.py
, which is a very good document to go deeper into Kivy apps.