Kivy BoxLayout 将小部件对齐到顶部边框

Kivy BoxLayout align widgets to the top border

我正在使用以下 Kivy 代码创建带按钮的 BoxLayout:

BoxLayout:
    orientation: "vertical"
    width: 200
    size_hint_x: None

    Button:
        size_hint_y: None
        height: 30
        text: 'btn1'

    Button:
        size_hint_y: None
        height: 30
        text: 'btn2'

    Button:
        size_hint_y: None
        height: 30
        text: 'btn3'

但是按钮粘在底部边缘,我怎样才能将它们推到布局的顶部边缘?

可以为此使用 StackLayout,以确保按钮从上到下。

您也可以尝试在 BoxLayout 中使用填充

来自 kivy BoxLayout 文档:

Padding between layout box and children: [padding_left, padding_top, padding_right, padding_bottom].

padding also accepts a two argument form [padding_horizontal, padding_vertical] and a one argument form [padding].

Changed in version 1.7.0: Replaced NumericProperty with VariableListProperty.

padding is a VariableListProperty and defaults to [0, 0, 0, 0].

例如,您的可能看起来像:

BoxLayout:
    orientation: "vertical"
    width: 200
    size_hint_x: None
    padding: 0, 0, 0, bottom_padding_here

无论屏幕大小如何,您将其设置为始终将按钮放在正确的位置是另一回事。但我相信完全可行。

如果您稍后要添加或删除按钮,您将调整填充等。

你也可以在最后放一个空的Widget来占用space。

BoxLayout:
    orientation: "vertical"
    width: 200
    size_hint_x: None

    Button:
        size_hint_y: None
        height: 30
        text: 'btn1'

    Button:
        size_hint_y: None
        height: 30
        text: 'btn2'

    Button:
        size_hint_y: None
        height: 30
        text: 'btn3'

    Widget: