Kivy is an open source Python library that can make you develop fastly rapid applications
that use innovative user interfaces, such as multi-touch apps. In this first one of a serie of posts we will see how to install Kivy and do our first Hello World.
I installed Kivy 2.0 just with this command using pip
pip install kivy
That’s all. It worked. Now let’s make our first program: “Hello World”.
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()
Pong App
This example is provided by the kivy site itself. Let’s follow it along.
from kivy.app import App from kivy.uix.widget import Widget class PongGame(Widget): pass class PongApp(App): def build(self): return PongGame() if __name__ == '__main__': PongApp().run()
Let’s see what’s in there:
- import App and Widget classes from kivy.app and kivy.uix.widget
- create a class PongGame – inherit Widget
- create a PongApp class – inherit from App
- start with PongApp().run() – method inherit by Widget
The .kv file to make the graphic
Put this file in the same dir of the python script and you will get the graphic layout automatically loaded.
#:kivy 1.0.9 <PongGame>: canvas: Rectangle: pos: self.center_x - 5, 0 size: 10, self.height Label: font_size: 70 center_x: root.width / 4 top: root.top - 50 text: "0" Label: font_size: 70 center_x: root.width * 3 / 4 top: root.top - 50 text: "0"
We got a rectangle and 2 labels, like you see in the picture below. The rectangle is the line, the labels contains the zeros.
Remember to call pong the .kv file, because you called PongApp the class in the .py file. You must call it like the part (pong) that is before App in the name of the class.
:kivy 1.0.9
This line is requirend in every kivy file.
kv files uses indentation like python for its nested blocks.
Widget rule
<PongApp> is a Widget rule. It means that every istance of this class will have the line in the middle and the 2 zeros.
Inside the widget rule (PongApp in this example) you define blocks with style and widgets.
canvas:
It defines how the widgets are rendered. A good thing of kivy is that its widgets resizes as the window is resized, so it adapts automatically to the size of the window that makes it very handy when the code runs on differet devices.
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame