Reputation: 67
I'd like to know how to access an instace object from a class I have defined from both my Kv Language child widgets and my widgets classes inside my Python file.
If I instantiate my object in my App's class, my Kv Language file has access to it and my widgets classes don't. But when I make this object global (outside my App's class), all my classes access it, but my Kv Language child widgets don't. I made the following code the make it clear:
My Python file:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
class Person():
def __init__(self, name):
self.name = name
def getName(self):
return self.name
class MyLayout(BoxLayout):
def getPerson1Name(self):
return person1.getName()
person1 = Person('Nik')
class MyApp(App):
person2 = Person('Jackie')
def build(self):
return MyLayout()
if __name__ == "__main__":
MyApp().run()
My Kv Language file:
<MyLayout>:
BoxLayout:
orientation: 'vertical'
Label:
id: nameDisplay
Button:
text: 'Display person1\'s name'
on_press: nameDisplay.text = root.getPerson1Name()
Button:
text: 'Display person2\'s name'
on_press: nameDisplay.text = app.person2.getName()
As you can see, person1 can be accessed from MyLayout class and person2 from my Kv Language file, but if I swap these objects, it won't work. Does someone know how I'll make an object accessebile from these two mediums?
Upvotes: 0
Views: 1824
Reputation: 8213
You can use App.get_running_app():
class MyLayout(BoxLayout):
def getPerson1Name(self):
return App.get_running_app().person2.getName()
It's generally bad practice to use global variables.
Upvotes: 3