Kivy: get parent inside widget which is added in python
<p>How do I get the reference to a parent inside a widget that is not added by kvlang but in python.
Normally you would just call <code>self.parent</code> however that returns <code>Null</code> if the widget is added in python to the parent.</p>

<p>An example:</p>

<pre><code>import kivy
kivy.require('1.9.0') # replace with your current kivy version !

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.clock import Clock

kvlang = '''
&lt;ScreenManagement&gt;:
    ScreenOne:

&lt;ScreenOne&gt;:
    name: 'First'


&lt;ScreenTwo&gt;:
    name: 'Second'

'''


class ScreenManagement(ScreenManager):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)

        def setup(*args):
            self.add_widget(ScreenTwo())    #add ScreenTwo later in python

        Clock.schedule_once(setup)

class ScreenOne(Screen):
    def __init__(self,**kwargs):
        super().__init__()

        def setup(*args):
            print("Parent of ScreenOne: {}".format(self.parent))        #this is working
        Clock.schedule_once(setup)

class ScreenTwo(Screen):
    def __init__(self,**kwargs):
        super().__init__()

        def setup(*args):
            print("Parent of ScreenTwo: {}".format(self.parent))        #this is not working, self.parent will return None
        Clock.schedule_once(setup)



class MyApp(App):

    def build(self):
        Builder.load_string(kvlang)
        return ScreenManagement()


if __name__ == '__main__':
    MyApp().run()
</code></pre>

<p>This will return:</p>

<pre><code>Parent of ScreenOne: &lt;__main__.ScreenManagement object at 0x7f98a3fddb40&gt;
Parent of ScreenTwo: None
</code></pre>

<p>Widgets added with <code>add_widget</code> actually has a valid reference to their parent:</p>

<pre><code>from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen

from kivy.lang import Builder
Builder.load_string('''
&lt;ScreenTwo&gt;
    Label:
        text: 'Hello, world'    
''')

class ScreenManagement(ScreenManager):
    def __init__(self,**kwargs):
        super(ScreenManagement, self).__init__(**kwargs)
        screen = ScreenTwo()

        print(screen.parent)
        self.add_widget(screen)  
        print(screen.parent)


class ScreenTwo(Screen):
    def on_touch_down(self, *args):
        print(self.parent)


class MyApp(App):
    def build(self):
        return ScreenManagement()


if __name__ == '__main__':
    MyApp().run()
</code></pre>

<p>It's just not available in their <code>__init__</code> method.</p>

python kivy