pythonclasskivykivy-languageids

Python Kivy can't access id from another class


I can't get widget from another class by id. I tried app.root.ids.first_lbl.text, but it didn't work. Is there any way to do this?

Here is my code:

main.py:

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


class MainWidget(Widget):
    pass

class SecondWidget(BoxLayout):
    pass

class MyApp(App):
    def build(self):
        return MainWidget()


if __name__ == "__main__":
    MyApp().run()

my.kv:

<MainWidget>
    BoxLayout:
        size: root.width, root.height

        BoxLayout:
            Label:
                id: first_lbl
                text: "TEXT123"

        SecondWidget:

<SecondWidget>:
    Label:
        text: app.root.ids.first_lbl.text

Solution

  • Here is a hack that will work:

    <MainWidget>
        BoxLayout:
            size: root.width, root.height
    
            BoxLayout:
                Label:
                    id: first_lbl
                    text: "TEXT123"
    
            SecondWidget:
                t1: first_lbl.text  # set the t1 property of SecondWidget to the text of first_lbl
    
    <SecondWidget>:
        t1: ''
        Label:
            text: root.t1  # use the t1 property of SecondWidget