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'
Widgets in Kivy are organized in trees. Your application has a root widget , which usually has children that can have children of their own. Children of a widget are represented as the children attribute, a Kivy ListProperty .
Kivy is a free and open source Python framework for developing mobile apps and other multitouch application software with a natural user interface (NUI). It is distributed under the terms of the MIT License, and can run on Android, iOS, Linux, macOS, and Windows. Kivy.
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
Inside a kv file, root always refers to a parent with angle brackets. There can therefore be multiple roots which you can refer to in a kv file, depending on where you are in the file.
# Root here refers to the parent class in angle brackets
<SomeClass>:
BoxLayout:
Label:
text: root.label_text
# and further down in the same kv file, this other
# class is also a root.. here root refers to
# this class
<SomeOtherClass/Widget/LayoutEtc>:
BoxLayout:
Label:
text: root.label_text
In a python file then, these classes could be represented like so:
class SomeClass:
label_text = StringProperty("I'm a label")
def __init__(**kwargs):
super(SomeClass, self).__init__(**kwargs)
b = BoxLayout()
l = Label(text=self.label_text)
b.add_widget(l)
self.add_widget(b)
# now we're set up like the first class in the above kv file
Now look above and compare how the kv file assigned the text to the label, and how it's done in the python file above. In kv it was root.label_text
, but above, the class uses self
. As in, text=self.label_text
. It's also used when adding the boxlayout, self.add_widget(b)
. self
is a way of referring to the current instance of the class.
That's how you basically refer to what would be 'root' in the kv file, but in the python file.
If you don't know why self
is used, then I advise learning about classes in python, as that's where the explanation to that lies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With