python – How to use different .kv files in an application with Kivy?

Question:

I'm trying to create a game using Kivy in Python language and I would like to know how I can use different .kv files to be used in the application as stages for the game. Example:

main.py
game.kv
fases/
   fase1.kv
   fase2.kv
   fase3.kv
   ...

Is it possible to split my .kv file into several others as in the example above? If yes, how can I do it?

Answer:

Yes, it's possible.

In Python code, remember to load the files using the Builder:

from kivy.lang import Builder

Builder.load_file('caminho_para_arquivo_kivy.kv')

In the main kv file (main.kv), you can import other kv files.

<main_kv>: 

    cols: 1

    AnchorLayout: 
        anchor_x: 'left'
        anchor_y: 'center'

        OutroKv: 
            size_hint: [None, None] 
            size: [app.x, app.y]

In the other Kv file:

<OutroKv@BoxLayout>: 
    Button: 
        text: 'Outro KV'

This way you can better modulate your application's graphical interface.

Scroll to Top