Python | Kivy .kv File
As when we write the application in Python kivy, to write all the things on the same code make a mess in the code and it is hard to understand that by someone another. Also writing a large code makes hard to maintain the construction of the widget tree and explicit the declaration of bindings.
The KV language, allows us to create own widget tree in a declarative way and to bind the widget properties to each other or to callbacks in a natural way.
???????? Kivy Tutorial – Learn Kivy with Examples.
How to load kv file:
There are 2-ways to load the .kv file into code or Application
- By name convention method-
While writing code we will make the App class. For this method, the name of the file and the app class is same and save the kv file with appclassname.kv.
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:
classnameApp ---> classname.kv
If this file defines a Root Widget it will be attached to the App’s root attribute and used as the base of the application widget tree.
The sample code on how to use .kv file in kivy is given below:
- .kv file code save with the same name as the app class –
- Builder method-
For this method to use you first have to import Builder by writing
from kivy.lang import builder
Now by the builder you can directly load the whole file as a string or as a file. By doing this for loading .kv file as a file:
or, for loading, kv file as a string: