You can learn more in the KV language guide.
Use the KV Language
00:00 Using the KV language. Kivy also provides a design language called KV that you can use with your Kivy applications. The KV language lets you separate your interface design from the application’s logic.
00:15 This follows the separation of concerns principle and is part of the Model-View-Controller architectural pattern. On-screen, you’ll see a simple example, which will make use of the KV language.
This code might look a bit odd at first glance, as it creates a
Button without setting any of its attributes or binding it to any events.
What’s happening here is that Kivy will automatically look for a file that has the same name as the class in lowercase, without the
App part of the class name.
In this case, the class name is
ButtonApp, so Kivy will look for a file named
button.kv. If that file exists and is properly formatted, then Kivy will use it to load up the user interface.
Go ahead and create the file and add the code seen on-screen. This matches the
Button call in your Python code. It tells Kivy to look into the instantiated object for a button definition.
This sets the button
text, and here you set the width and height with
size_hint tells Kivy the proportions to use when creating the widget. It takes two numbers. The first number is the
x size hint and refers to the width of the control.
The second number is the
y size hint and refers to the height of the control. Both of these numbers can be anywhere between
The default value for both hints is
1. Next, you set the buttons position with
pos_hint. Here, you tell Kivy to center the widget on the x and y axes with a value of
.5 for each.
This line sets the
on_press event handler. To tell Kivy where the event handler is, you use
app.on_press_button(). Here, Kivy will look in the
Application class for a method called
With both files saved, running the
kv_example script works as expected, with Kivy pulling the information from
button.kv behind the scenes and creating the layout as expected.
.on_press_button() working as desired,
02:51 you can set up all your widgets and layouts inside one or more KV language files. The KV language also supports importing Python modules in KV, creating dynamic classes, and much more.
03:05 For full details, check out Kivy’s guide to the KV language. Now you’re ready to create a real application, and that’s what you’ll be doing in the next section of the course.
Become a Member to join the conversation.