Kivy – File Syntax


Kivy – File Syntax



”;


Kivy framework provides a concise and declarative approach to define the widget structure and appearance, with the use of Kivy Language (also known as Kv language). It is a declarative language, used exclusively for building user interfaces in Kivy applications. Its main advantage is that you can separate the UI design from the application logic written in Python.

The UI design is defined in a text file which must have a “.kv” extension. It contains the hierarchical sequence of widgets in the application window. The file adapts a tree-like structure, showing the parent-child-sibling relationship among the widgets. Below each widget, its properties, events and event handlers are specified.

The kv design language stipulates the following conventions while creating a “.kv” file, so that Python and the Kivy framework can identify and load the appropriate widget structure −

  • Name of the file must be in lowercase

  • It must match with the main class in your application. This class is inherited from the App class.

  • If the name of the class ends with “app” or “App” (for example, HelloApp), the “.kv” file must exclude “app” from its name. It means, for HelloApp class, the name of the “.kv” file must be “hello.kv”.

  • The “.kv” file must be in the same folder in which the Python application file (.py) is present.

While using the “.kv” file, the App class doesn”t override the build() method. Declaring a class simply with a pass statement is enough. When the run() method is invoked, Kivy automatically loads the UI from the respective “.kv” file.

Let us first remove the build() method from the HelloApp class −

Example


from kivy.app import App
class HelloApp(App):
   pass
app = HelloApp()
app.run()

The User interface is defined in “hello.kv” file in the same folder. We have a top level BoxLayout with vertical orientation, under which two labels are placed. Save the following script as “hello.kv” file


BoxLayout:
   orientation: ''vertical''
   Label:
      text: ''Python Kivy Tutorial''
      font_size: ''30pt''
   Label:
      text: ''From TutorialsPoint''
      font_size: ''50''
      color: (1,0,0,1)

Now, if you run the “hello.py” program, it will produce the following output −

Output


kivy file syntax

In latter chapters, we shall learn how to add event handlers to the widgets in the “.kv” file.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *