有没有办法在父级(布局)之上添加一个小部件?

Is there any way to add a widget above the parent(Layout)?

嘿,我最近开始使用 python / kivy 编程。 我有一个基本问题,我找到的文档无法解决。

我想在我的根目录 (ScreenLayout) 之上添加一个自定义函数 (InitiateGraph)。 在此函数中,我正在使用 matplotlib 绘制图形,该图形是通过调用应用程序生成的。它应该是这样的:

_ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  
|here should be the plotted graph from InitiateGraph|  
_ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  
_ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  
|  here should follow the GridLayout (ScreenLayout)   |  
_ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _  _ _ 

目前这两个街区是颠倒的。 请参阅以下简约示例。

Python-代码:

class ScreenLayout(GridLayout):

    def __init__(self, *args, **kwargs):
        super(ScreenLayout, self).__init__(*args, **kwargs)
        self.add_widget(self.InitiateGraph())

    def InitiateGraph(self):
        ...

class TestApp(App):

    def build(self):
        return ScreenLayout()

Test = TestApp()
Test.run()

Kivy 代码:

<ScreenLayout>:
    rows: 3
    BoxLayout:
    BoxLayout:

有办法吗?

有几种方法可以做到这一点。

您可以使用 add_widgetindex 参数将小部件放置在 ScreenLayout 的子项中的特定位置。但这很少是好方法,因为当您出于其他原因更新布局时它很容易中断。

更好的方法是使用带有 ID 的容器小部件,这样您就可以轻松引用它并在其中添加您的小部件。

<ScreenLayout>:
    rows: 3
    BoxLayout:
        id: graph_container
    BoxLayout:
    BoxLayout:

然后

def __init__(self, *args, **kwargs):
    super(ScreenLayout, self).__init__(*args, **kwargs)
    self.ids.graph_container.add_widget(self.InitiateGraph())