Search code examples
pythonkivykivy-language

Kivy: How to change the attribute's value like text of label from current screen in another screen


I tried to change the text of another screen from current screen. But it didn't work

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.properties import ObjectProperty
from kivy.lang.builder import Builder


Builder.load_string("""
<Input_Screen>:
    input: input
    BoxLayout:
        orientation : "vertical"
        TextInput:
            id: input
            text: "Changed"
        Button:
            text: "Enter"
            on_press : root.clicked()
            
<Display_Screen>:
    nice: nice
    BoxLayout:
        orientation : "vertical"
        Label:
            id: nice
            text: "NotChanged"
    

""")


class Input_Screen(Screen):
    input = ObjectProperty(None)
    def clicked(self):
        Display_Screen().change()

class Display_Screen(Screen):
    nice = ObjectProperty(None)
    def change(self):
        print(self.nice.text) #Checking the Current text of The Label
        print(Input_Screen().input.text) #Checking What do we want to change
        self.nice.text = Input_Screen().input.text
        print(self.nice.text) #Checking if it has change or not
        MyApp().sm.current = "Ds" #Changing Screen to Display_Screen
        print(self.nice.text) #Checking if it has change or not


class MyApp(App):
    sm = ScreenManager()
    def build(self):
        self.sm.add_widget(Input_Screen(name="Is"))
        self.sm.add_widget(Display_Screen(name="Ds"))
        return self.sm

MyApp().run()

What I get in My console:

NotChanged #Checked the Current text of The Label
Changed #Checked What do we want to change
Changed #Checked if it has change or not
Changed #Checked if it has change or not

It says that my Label's text has been changed but when it goes to the next screen it hasn't been changed.

Display_Screen

Anyone knows whats the problem? Help me please


Solution

  • Whenever you use a construction like ClassName(), you are creating a new instance of ClassName. You are doing this in your change() method and in your clicked() method. Whenever you do that, you are referencing that new instance, and not the instance that is in your GUI.

    To fix that, change:

    def clicked(self):
        Display_Screen().change()
    

    to:

    def clicked(self):
        self.manager.get_screen('Ds').change()
    

    and in your change() method, replace:

    Input_Screen()
    

    with:

    self.manager.get_screen('Is')
    

    and replace"

    MyApp()
    

    with:

    App.get_running_app()