Search code examples
pythonclassmethodskivyself

Kivy call SELF method from another class


In this very simple kivy python program I try to change text label from Window2 class using method in Window1 class. When I call in Window2 for Window1 method, method is launched, but self.ids .... line is not done.

Any idea what must be changed to make the self.ids.label1.text = "DONE" work?

python file

from kivy.uix.boxlayout import BoxLayout


class ParentWindow(BoxLayout):
    pass


class Window1(BoxLayout):

    def update(self):
        print("This print works, but next line not ...")
        self.ids.label1.text = "DONE"


class Window2(BoxLayout):

    def try_change(self):
        Window1().update()


class MyProgramApp(App):
    def build(self):
        return ParentWindow()


MyProgramApp().run()

kivy file

<ParentWindow>:
    Window1:
    Window2:

<Window1>:
    orientation: "vertical"
    Label:
        id: label1
        text: "Try to change me"
    Button:
        text: "Works fine from self class"
        on_press: root.update()

<Window2>:
    Button:
        text: "Lets try"
        on_press: root.try_change()

Solution

  • I have found solution:

    .py

    from kivy.app import App
    from kivy.uix.boxlayout import BoxLayout
    
    
    class ParentWindow(BoxLayout):
        pass
    
    
    class Window1(BoxLayout):
    
        def update(self):
            print("This print work, but next line not ...")
            self.ids.label1.text = "DONE"
    
    
    class Window2(BoxLayout):
    
        def try_change(self):
            self.parent.ids.win1.update()
    
    
    class MyProgramApp(App):
        def build(self):
            return ParentWindow()
    
    
    MyProgramApp().run()
    

    .kv

    <ParentWindow>:
        Window1:
            id: win1
        Window2:
    
    
    <Window1>:
        orientation: "vertical"
        Label:
            id: label1
            text: "Try to change me"
        Button:
            text: "Works fine from self class"
            on_press: root.update()
    
    <Window2>:
        Button:
            text: "Lets try"
            on_press: root.try_change()