Application example using build() + return
Application from a .kv in a Template Directory
Texture Wrapping and Coordinates Example
Multistroke Recognition Database Demonstration
Touch Tracer Line Drawing Demonstration
Compatibility module for Python 2.7 and 3.3
Kivy module for binary dependencies.
CGL: standard C interface for OpenGL
Native support for HID input from the linux kernel
Native support of Wacom tablet from linuxwacom driver
Native support of MultitouchSupport framework for MacBook (MaxOSX platform)
Native support for Multitouch devices on Linux, using libmtdev.
Auto Create Input Provider Config Entry for Available MT Hardware (linux only).
Common definitions for a Windows provider
Support for WM_PEN messages (Windows platform)
Support for WM_TOUCH messages (Windows platform)
NO DOCUMENTATION (module kivy.uix.recycleview)
Accessing Widgets defined inside Kv lang in your python code
Re-using styles in multiple widgets
As your application grow more complex, its common that the construction of widget trees and explicit declaration of bindings, becomes verbose and hard to maintain. TheKVLanguage is a attempt to overcome these short-comings.
TheKVlanguage (sometimes called kvlang, or kivy language), allows you to create your widget tree in a declarative way and to bind widget properties to each other or to callbacks in a natural manner. It allows for very fast prototyping and agile changes to your UI. It also facilitates a good separation between the logic of your application and its User Interface.
There are two ways to load Kv code into your application:
Kivy looks for a Kv file with the same name as your App class in lowercase, minus App if it ends with App e.g:
If this file defines aRoot Widgetit will be attached to the Appsrootattribute and used as the base of the application widget tree.
Builder: You can tell Kivy to directly load a string or a file. If this string or file defines a root widget, it will be returned by the method:
A Kv source constitutes ofrules, which are used to describe the content of a Widget, you can have onerootrule, and any number ofclassortemplaterules.
Therootrule is declared by declaring the class of your root widget, without any indentation, followed by:and will be set as therootattribute of the App instance:
Aclassrule, declared by the name of a widget class between and followed by:, defines how any instance of that class will be graphically represented:
Rules use indentation for delimitation, as python, indentation should be of four spaces per level, like the python good practice recommendations.
There are three keywords specific to Kv language:
: always refers to the instance of your application.
: refers to the base widget/template in the current rule
: always refer to the current widget
There are two special syntaxes to define values for the whole Kv context:
To access python modules and classes from kv,
To declare the widget has a child widget, instance of some class, just declare this child inside the rule:
The example above defines that our root widget, an instance ofMyRootWidget, which has a child that is an instance of theBoxLayout. That BoxLayout further has two children, instances of theButtonclass.
A python equivalent of this code could be:
Which you may find less nice, both to read and to write.
Of course, in python, you can pass keyword arguments to your widgets at creation to specify their behaviour. For example, to set the number of columns of agridlayout, we would do:
To do the same thing in kv, you can set properties of the child widget directly in the rule:
The value is evaluated as a python expression, and all the properties used in the expression will be observed, that means that if you had something like this in python (this assumeselfis a widget with adataListProperty):
To have your display updated when your data change, you can now have just:
Widget names should start with upper case letters while property names should start with lower case ones. Following thePEP8 Naming Conventionsis encouraged.
You can bind to events in Kv using the : syntax, that is, associating a callback to an event:
You can pass the values dispatched by the signal using theargskeyword:
More complex expressions can be used, like:
This expression listens for a change incenter_x,center_y, andtexture_size. If one of them changes, the expression will be re-evaluated to update theposfield.
You can also handleon_events inside your kv language. For example the TextInput class has afocusproperty whose auto-generatedon_focusevent can be accessed inside the kv language like so:
Kv lang can be used to define the canvas instructions of your widget like this:
And they get updated when properties values change.
Of course you can usecanvas.beforeandcanvas.after.
In a widget tree there is often a need to access/reference other widgets. The Kv Language provides a way to do this using ids. Think of them as class level variables that can only be used in the Kv language. Consider the following:
Anidis limited in scope to the rule it is declared in, so in the code aboves_butcan not be accessed outside theMySecondWidgetrule.
When assigning a value toid, remember that the value isnt a string. There are no quotes: good -id:value, bad -id:value
Anidis aweakrefto the widget and not the widget itself. As a consequence, storing theidis not sufficient to keep the widget from being garbage collected. To demonstrate:
Although a reference tolabel_widgetis stored inMyWidget, it is not sufficient to keep the object alive once other references have been removed because its only a weakref. Therefore, after the remove button is clicked (which removes any direct reference to the widget) and the window is resized (which calls the garbage collector resulting in the deletion oflabel_widget), when the add button is clicked to add the widget back, aReferenceError:weakly-referencedobjectnolongerexistswill be thrown.
To keep the widget alive, a direct reference to thelabel_widgetwidget must be kept. This is achieved usingid.__self__orlabel_widget.__self__in this case. The correct way to do this would be:
txt_inptis defined as aObjectPropertyinitialized toNoneinside the Class.
At this point self.txt_inpt isNone. In Kv lang this property is updated to hold the instance of theTextInputreferenced by the idtxt_inpt.:
From this point onwards,self.txt_inptholds a reference to the widget identified by the idtxt_inputand can be used anywhere in the class, as in the functioncheck_status. In contrast to this method you could also just pass theidto the function that needs to use it, like in case off_butin the code above.
There is a simpler way to access objects withidtags in Kv using theidslookup object. You can do this as follows:
When your kv file is parsed, kivy collects all the widgets tagged with ids and places them in thisself.idsdictionary type property. That means you can also iterate over these widgets and access them dictionary style:
Although theself.idsmethod is very concise, it is generally regarded as best practice to use the ObjectProperty. This creates a direct reference, provides faster access and is more explicit.
Hello world, watch this text wrap inside the button
Even absolute is relative to itself
Repeating the same thing over and over in a comp = fail
Instead of having to repeat the same values for every button, we can just use a template instead, like so:
Hello world, watch this text wrap inside the button
Even absolute is relative to itself
repeating the same thing over and over in a comp = fail
This class, created just by the declaration of this rule, inherits from the Button class and allows us to change default values and create bindings for all its instances without adding any new code on the Python side.
Because both classes share the same .kv style, this design can be simplified if we reuse the style for both widgets. You can do this in .kv as follows. In my.kv:
By separating the class names with a comma, all the classes listed in the declaration will have the same kv properties.
One of aims of the Kivy language is toSeparate the concernsof presentation and logic. The presentation (layout) side is addressed by your kv file and the logic by your py file.
Lets start with a little example. First, the Python file namedmain.py:
Create a controller that receives a custom widget from the kv lang file.
Add an action to be called from the kv lang file.
My label after button press
In this example, we are creating a Controller class with 2 properties:
In addition, we are creating ado_action()method that will use both of these properties. It will change theinfotext and change text in thelabel_widwidget.
Executing this application without a corresponding.kvfile will work, but nothing will be shown on the screen. This is expected, because theControllerclass has no widgets in it, its just aFloatLayout. We can create the UI around theControllerclass in a file namedcontroller.kv, which will be loaded when we run theControllerApp. How this is done and what files are loaded is described in thekivy.app.App.load_kv()method.
One label and one button in a verticalBoxLayout. Seems very simple. There are 3 things going on here:
Using data from theController. As soon as theinfoproperty is changed in the controller, the expressiontext:Mycontrollerinfois:+will automatically be re-evaluated, changing the text in theButton.
Giving data to theController. The expressionid:my_custom_labelis assigning the createdLabelthe id ofmy_custom_label. Then, usingmy_custom_labelin the expressionlabel_wid:my_custom_labelgives the instance of thatLabelwidget to yourController.
Creating a custom callback in theButtonusing theControllerson_pressmethod.
are reserved keywords, useable anywhere.
represents the top widget in the rule and
You can use any id declared in the rule the same as
. For example, you could do this in the
And thats that. Now when we runmain.py,controller.kvwill be loaded so that theButtonandLabelwill show up and respond to our touch events.