首页 > 解决方案 > 在 RelativeLayout 中嵌入 GridLayout

问题描述

我正在与 Kivy 斗争,以使其正确显示按钮。我想创建一个在 for 循环中创建的按钮网格,并将它们显示在 RelativeLayout 内的网格中。这导致按钮堆叠在另一个之上。请看下面:

主要.py:

import kivy
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.lang.builder import Builder
from kivy.uix.button import Button

Builder.load_file('TopMenu.kv')
Builder.load_file('BottomMenu.kv')
Builder.load_file('Center.kv')
Builder.load_file('Left.kv')

class mainHolder(AnchorLayout):
    pass

class MainApp(App):
    def build(self):
        self.title = "NAZWA APLIKACJI"
        #return Label(text = "Hello, world")
        return mainHolder()


if __name__ == '__main__':
    MainApp().run()

主文件.kv

<MainHolder>:
    anchor_x: 'left'
    anchor_y: 'top'
    BoxLayout:
        orientation: 'vertical'
        #anchor_x: 'left'
        #anchor_y: 'top'

        TopMenu:
            id: _top_menu
            #size_hint: 1, 0.1
            #height: 0, 1
            canvas.before:
                Color:
                    rgba:0.5, 0.5, 0.5, 0.5
                Rectangle:
                    pos: self.pos
                    size: self.size
        Center:
        BottomMenu:

中心.kv:

<Center@GridLayout>:
    cols: 2
    size_hint: 1, 1
    Left:
    Label:
        text: 'prawa'

左.py:

from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.button import Button

class Left(RelativeLayout):
    def __init__(self, **kwargs):
        super(RelativeLayout, self).__init__(**kwargs)
        print("Left is alive!")

        for i in range(0, 11):
            print("Adding button: " + str(i))
            but = Button(text="X" + str(i))
            self.add_widget(but)

最后,left.kv:

#:import Left Left
<Left>:
    size_hint: 1.3, 1
    pos_hint: 1, 1

这种方法创建了以下内容: StackBtns 我尝试将 RelativeLayout 更改为 GridLayout,但按钮看起来大致相同,不同之处在于它们位于最左下角,所以我猜 RelativeLayout 是开始将它们定位的好方法一个正确的地方。

所以我在 Left.kv 中手动添加了一些 GridLayout,如下所示:

<Left>:
    size_hint: 1.3, 1
    pos_hint: 1, 1

    GridLayout:
        cols: 4
        Button:
            text: "t2"
        Button:
            text: "t2"
        Button:
            text: "t2"
        Button:
            text: "test"

这很好用。因此,在此之后,我创建了另一个类,这次是 GridLayout,但这根本不起作用 - 抱歉,我没有代码了,删除它,因为它没有结果。此外,如上所示添加 GridLayout 不会导致 add_widget() 将其添加到正确的位置。你们能帮帮我吗?我对此感到非常沮丧,谷歌没有提供任何合理的答案。我想从这个应用程序设计的一开始这可能是错误的方法,但老实说,我不知道“好”点可能是什么。


约翰安德森谢谢你!这就像一个魅力。我是如此接近,但到目前为止,我永远不会找到这个。干杯! :-)

标签: pythonpython-3.xkivy

解决方案


我认为使用 aGridLayout是一种合理的方法。我稍微修改了你的Left课程来做到这一点:

from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

class Left(GridLayout):
    def __init__(self, **kwargs):
        # corrected the call to super
        super(Left, self).__init__(**kwargs)

        print("Left is alive!")

        # set the number of columns in this grid
        self.cols = 5

        for i in range(0, 11):
            print("Adding button: " + str(i))
            but = Button(text="X" + str(i))
            self.add_widget(but)

推荐阅读