Daniel Qiu
Daniel Qiu

Reputation: 13

How to access variables from different screens in python kivy?

As title states, I would like to figure out how I would retrieve an object property from 1 screen to another. I have one screen that has an object property but I cant seem to find a way to access that object property in a different screen/class. For example:

class windowOne(Screen):
    myVar = ObjectProperty("Hello")
    pass
class windowTwo(Screen):
    pass

I would like to access myVar in windowTwo. Any ideas? I have my full code if you would like me to post it.

Upvotes: 1

Views: 768

Answers (1)

John Anderson
John Anderson

Reputation: 39152

In order to access a variable of windowOne, you first need a reference to the instance of windowOne that is in your App. Typically, you get that reference from the ScreenManager.

If you are accessing it from a method of another Screen, you can get a reference to the ScreenManagerlike this:

screen_manager = self.manager

If you are not in a method of another Screen, you can often get the reference to the ScreenManager as:

screen_manager = App.get_running_app().root

The above assumes that the ScreenManager is the root widget of the App.

Once you have the ScreenManager, you can use the get_screen() method to get a reference to windowOne:

window_one = screen_manager.get_screen('Name of WindowOne Screen')

where Name of WindowOne Screen is the name that you assign to the WindowOne Screen.

And, finally, the myVar variable is accessed by:

window_one.myVar

Upvotes: 1

Related Questions