Search code examples
pythonpython-3.xkivykivy-language

How can I load text into my screen on screen change in Kivy?


I am working on an application where one of my screens has some labels and text input fields. Whenever the user navigates to this screen, I'd like for some kind of load() function to check for data in a JSON file. If it finds data, it can load this data into the screen in the respective text input fields. If not, then no worries.

I am able to store and retrieve data form a JSON file easily enough, but for the life of me I can't seem to figure out how to store this information into the screen in question whenever I navigate there! Is there some way to have a function run every time the screen appears that will fill in these text input fields?

texttest.kv

WindowManager:
    MainWindow:
        id: main_screen
    SetupWindow:
        id: setup_screen

<SetupWindow>
    name: "setup"
    hostpy: hostkv
    GridLayout:
        cols:1

        GridLayout:
            cols: 2

            Label:
                text: "Host or IP: "

            TextInput:
                id: hostkv
                multiline: False

texttestapp.py

...
...
...
class MainWindow(Screen):
    pass


class SetupWindow(Screen):
    hostpy = ObjectProperty(None)

    def __init__(self,**kwargs):
        super(SetupWindow,self).__init__(**kwargs)
        self.hostpypy.Text = "This is a test"

class WindowManager(ScreenManager):
    pass

...
...
...

As you can see, I tried with __init__(self,**kwargs), but this seems to be the wrong solution. What can I do to accomplish what I need?


Solution

  • I was able to find the answer: Kivy actually has it's own API for this, which I had overlooked. Specifically, you can use on_pre_enter() or on_enter() to get this to work. The documentation for it is located here: https://kivy.org/doc/stable/api-kivy.uix.screenmanager.html#kivy.uix.screenmanager.Screen