2 min read

Python Kivy Framework

Kivy is an open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. It runs on Linux, Windows, OS X, Android, iOS, and Raspberry Pi.

Installation

pip install kivy

Basic Application

To create a Kivy app, you subclass the App class and implement the build() method, returning a widget tree.

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

class MyApp(App):
    def build(self):
        return Label(text='Hello world')

if __name__ == '__main__':
    MyApp().run()

Layouts

Kivy uses layouts to arrange widgets. BoxLayout is one of the most common.

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

class MenuApp(App):
    def build(self):
        layout = BoxLayout(orientation='vertical')

        btn1 = Button(text='Start Game')
        btn2 = Button(text='Settings')
        btn3 = Button(text='Exit')

        layout.add_widget(btn1)
        layout.add_widget(btn2)
        layout.add_widget(btn3)

        return layout

if __name__ == '__main__':
    MenuApp().run()

Handling Events

You can bind callbacks to events like on_press.

def on_button_press(instance):
    print(f'You pressed {instance.text}')

btn = Button(text='Click Me')
btn.bind(on_press=on_button_press)

The KV Language

Kivy allows you to separate logic (Python) from presentation (KV Language).

myapp.py:

class LoginScreen(GridLayout):
    pass

myapp.kv:

<LoginScreen>:
    cols: 2
    Label:
        text: 'User Name'
    TextInput:
        multiline: False

programming/python/python