Search code examples
pythonmodel-view-controllerkivy

Is it required to use .kv files?


I'm trying to build a Kivy application using Python, but I'm finding it a little confusing and unnecessary to use .kv files, given that I can do everything in Python.

So my question is: is it a good practice to use .kv files? I read that is good because is it possible to separate the presentation logic (the .kv file) from the underlying application logic.

But I don't think this is gonna be a problem in my application, given that I'm separating my code in MVC, so I'm gonna have a Python file, where I'm gonna do all the View, rather than use the .kv, and all the logic is gonna be in another python files.


Solution

  • The Kivy framework is very rich and complex, so there are a multitude of possibilities for making an application. In fact, the KV language is designed to describe the interface, separating the backend from the frontend. For example, if you want to connect two widgets (a CheckBox and a Slider, for example), you can use this simple code to make the Slider active or inactive, depending on the state of the CheckBox (what's more, the properties contained in the kv file update automatically):

    TestUI:
    
    <TestUI@BoxLayout>:
        CheckBox:
            id: test_check_box
    
        Slider:
            disabled: True if test_check_box.state == "normal" else False
    

    You'll then have an interface where you can check and uncheck the CheckBox, and the Slider status will be updated. To do this in Python is more time-consuming: you'd have to bind the CheckBox's on_state property, define a function that would access the Slider's disabled property and change it every time the CheckBox's state changes. It's not complicated, but it takes longer to set up.

    If you've got a simple graphical interface to create, you use only Python, which avoids having to manage kv code, but the implementation of certain functions may be longer or even more complex. On the other hand, if you want to build a large-scale project with a sophisticated interface and lots of features, the kv language is essential, as it separates the backend from the frontend (making the code clearer) and makes it easy to connect widgets and layouts.

    I hope I've helped you.

    For more informations on Kivy framework and kvlang: https://kivy.org/doc/stable/guide/lang.html