Search code examples
python-2.7kivy

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


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'

Solution

  • My workaround was just to declare a global variable within the main App's build() method, something like global root and root = self.root since the root widget is accessible when you're in the App class. You can do the same thing with app.