Search code examples
pythonuser-interfacekivykivy-language

Which is the best way to link Widgets between .kv and .py file


I need some help in order to understand Kivy library. If i have to create a questionary like this example :enter image description here

But with a button in order to change page that will stay in the same position how I have to proceed? How I link lots of widgets together and the .kv file with the .py file? I'm trying but without any results.

For exemple i've written this code with a button and a colored background but it doesn't work :

.py Part :

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout

class Principale(BoxLayout):
    pass


class TryApp(App):
    def build(self):
        self.root = Builder.load_file('questionario.kv')
        Principale()


if __name__ == '__main__':
    PongApp().run()

.kv Part:

#:kivy 1.0.9
<Principale>:
    canvas:
        Color:
            rgb : 0.2549,0.73333,0.12156
        Rectangle:
            size:self.size
    size_hint : 1,1
    orientation:"vertical"
    padding : 30

    Button:
        text: "ciao"
        size_hint : 0.12,0.12

Thanks a lot


Solution

  • class TryApp(App):
        def build(self):
            self.root = Builder.load_file('questionario.kv')
            Principale()
    

    You need to return Principale here.

    return Principale()
    

    Not just create it.

    Also, you called your App TryApp but you're trying to run something called PongApp

    So this:

    PongApp().run()
    

    Should be:

    TryApp().run()
    

    So it should look like this in the end:

    class TryApp(App):
        def build(self):
            self.root = Builder.load_file('questionario.kv')
            return Principale()
    
    
    if __name__ == '__main__':
        TryApp().run()
    

    Note: It is harmless but you don't need to declare the kv as root. It already knows in this case.