【问题标题】:Is there any way to add a widget above the parent(Layout)?有没有办法在父级(布局)上方添加一个小部件?
【发布时间】:2018-08-10 13:16:05
【问题描述】:

嘿,我最近开始使用 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:

有没有办法做到这一点?

【问题讨论】:

    标签: python layout kivy kivy-language


    【解决方案1】:

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

    您可以使用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())
    

    【讨论】:

    • 哇,非常感谢,这正是我想要的:D
    • 太好了,那您可以将答案标记为已接受吗?所以寻找相同内容的其他人更容易看到它:)。
    • 哦,是的,肯定的事情:D必须熟悉网站上的工作方式^^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 2011-03-12
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多