我如何从 Python 引用 Kivy 的根控件?

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

在 Kivy 语言中,可以使用类似

的方式来引用根小部件
<RootWidget>:
    BoxLayout:
        SomeButton:
            on_press: print root

但是尝试从 Python 访问 root 是不可能的

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

并会导致

NameError: global name 'root' is not defined

或者如果使用 self.root

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

在 kv 文件中,root 总是用尖括号指代父级。因此,您可以在 kv 文件中引用多个根,具体取决于您在文件中的位置。

# 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

在 python 文件中,这些 class 可以这样表示:

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

现在看上面并比较 kv 文件如何将文本分配给标签,以及它在上面的 python 文件中是如何完成的。在 kv 中它是 root.label_text,但在上面,class 使用 self。如 text=self.label_text。添加框布局时也使用它,self.add_widget(b)self 是一种引用 class.

当前实例的方式

这就是您在 kv 文件中引用 'root' 而在 python 文件中的基本方式。

如果您不知道为什么使用 self,那么我建议您了解 python 中的 classes,因为这就是对它的解释所在。

我的解决方法是在主应用程序的 build() 方法中声明一个全局变量,类似于 global rootroot = self.root,因为当您在应用 class。你可以用 app.

做同样的事情

如果您想要应用程序中的实际根小部件,那么我会在任何小部件中使用以下内容 class...

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

只是为了把它放在那里。

Parent

Button:
  on_press: root.something()

Parent 共 parent:

Button:
  on_press: root.parent.something()