'How do I refer back to a kivy app class instance I have created?
from screen_selections import NameSelection
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager
class ScreenManagerApp(App):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.stage = {}
def build(self):
sm = ScreenManager()
sm.add_widget(NameSelection(name='name_selection'))
return sm
def write_to_console(self,input):
print(input)
if __name__ == '__main__':
ScreenManagerApp().run()
This above is my main class using Kivy. I asked a very long winded question previously, but I'm hoping this is more specific.
Based on what I am doing here, I am creating an instance of ScreenManagerApp directly at the bottom and using its run method, which is a method within the App parent class.
I want to be able to anywhere in my code, easily be able to refer back to this app instance (so in this case ScreenManagerApp()) as I will need to be storing variables here which can be referenced throughout the code, but advice says to not create them as global variables, this is better practice?
I understand I might need to explicitly name my instance so:
smApp = ScreenManagerApp()
smApp.run()
but then I still can't think of the best way to access this new instance I've created.
Solution 1:[1]
@JohnAnderson answered in the comments, but I wanted to close off the question.
There is a static method in App called get_running_app() which you can use anywhere in the code, and it will refer back to the instance that was created.
I've tested this and it works exactly as expected, so now, the variables that I need to persist through my classes I define in the app instance, and refer back to them easily using things such as:
App.get_running_app().example_variable
Thanks, Craig
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mr. T |
