User Tools

Site Tools


doc:appunti:prog:kivy

This is an old revision of the document!


Appunti Kivy

Python Code and KV Language

This is the kivyexample.py file:

#!/usr/bin/env python
from kivy.app import App
#kivy.require("1.8.0")
from kivy.uix.floatlayout import FloatLayout
 
class MyLayout(FloatLayout):
    pass
 
class KivyExampleApp(App):
    def build(self):
        return MyLayout()
 
if __name__ == "__main__":
    KivyExampleApp().run()

In the code above we derived a class named KivyExampleApp from the Kivy's App class. The Kivy code will automatically search for a file called kivyexample.kv, and it will parse it using the KV language. The name of the file is derived by the class name, making it all lowercase and removing the leftmost App part (if it exists). So this is the kivyexample.kv file:

<MyButton@Button>:
    font_size: 40
    color: 0,1,0,1
    size_hint: 0.3, 0.2

<MyLayout>:
    MyButton:
        text: "Pos 0, 0"
        pos_hint: {'x': 0, 'y': 0}
    MyButton:
        text: "Center x-y"
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}
    MyButton:
        text: "Pos right-top"
        pos_hint: {'right': 0.9, 'top': 0.3}
    MyButton:
        text: "Pos 0.5, 1.0"
        pos_hint: {'right': 0.5, 'top': 1.0}

In the Python code, the App constructor will return the MyLayout class, which is derived from the Kivy's FloatLayout class. The original class is an empty widget, but we added several buttons using the KV language.

Notice that MyLayout is derived from FloatLayout declaring it into the Python code, whereas the MyButton class is derived from the original Button class using the KV language, via the @Button construct. The result should be something like this:

KivyExampleApp

We used a KV file to define the graphic interface of our App, but it is possible to do that using only Python code, thus having only a single file. But doing as seen above has several advantages. First of all you can try to keep the graphical presentation and the code logic as much separate as possibile. Another advantage is that resizing the app's window, will resize all its contents automatically (if you are smart enough not to use absolute values); otherwise you have to bind the window-resize event to a function which should adjust each widget size and position.

doc/appunti/prog/kivy.1551092311.txt.gz · Last modified: 2019/02/25 11:58 by niccolo