How Can I Refer To Kivy's Root Widget From Python?

Tan Wang picture Tan Wang · Aug 23, 2015 · Viewed 11.7k times · Source

In Kivy language, it is possible to refer to the root widget with something like

<RootWidget>:
    BoxLayout:
        SomeButton:
            on_press: print root

but trying to access root from Python is impossible

class SomeButton(Button):
    def __init__(self, **kwargs):
        super(SomeButton, self).__init__(**kwargs)
        self.text = "Button"
        self.font_size = 15
    def on_press(self, *args):
        print root

and will result in

NameError: global name 'root' is not defined

or if using self.root,

AttributeError: 'SomeButton' object has no attribute 'root'

Answer

Jim Morris picture Jim Morris · Apr 23, 2017

If you want the actual root widget from the App then I use the following from within any Widget class...

from kivy.app import App
...
class myWidget(BoxLayout):
    app= App.get_running_app()
    app.root.whatever-you-want