将 BoxLayout 与 GridLayout 中的按钮居中

Centering BoxLayout with Buttons inside a GridLayout

我正在与 kivy 合作开展一个新项目。在设计我的 GUI 时,我遇到了以下问题。

我有一个 GridView 将我的 window 分成三个部分。顶部部分包含标题,中间部分应包含居中的按钮和标签。

这是我当前的 .kv 文件:

<Main>:    
rows: 3

Label:
    font_size: 25  
    text: "Some Headline"

GridLayout:
    rows: 2
    row_force_default: True
    row_default_height: 40
    col_force_default: True
    col_default_width: 200

    BoxLayout:
        orientation: 'horizontal'
        Button:
            text: "Button 1"
        Label:
            text: "Label 1"

    BoxLayout:
        orientation: 'horizontal'
        Button:
            text: "Button 2"
        Label:
            text: "Label 2"

结果 window 看起来像这样

但我想要的是这些带有 Bottons/Labels 的 BoxLayouts 位于 window 的中心。

我怎样才能完成这个或者我必须改变什么?

Kivy AnchorLayoutanchor_x: 'center'anchor_y: 'center'

结合使用

Kivy AnchorLayout » anchor_x

anchor_x

Horizontal anchor.

anchor_x is an OptionProperty and defaults to ‘center’. It accepts values of ‘left’, ‘center’ or ‘right’.

Kivy AnchorLayout » anchor_y

anchor_y

Vertical anchor.

anchor_y is an OptionProperty and defaults to ‘center’. It accepts values of ‘top’, ‘center’ or ‘bottom’.

例子

以下示例说明了 Kivy 的使用 AnchorLayout and Dynamic Classes

main.py

from kivy.base import runTouchApp
from kivy.lang import Builder

runTouchApp(Builder.load_string("""
<MiddleSection@AnchorLayout>:    # Dynamic class
    anchor_x: 'center'
    anchor_y: 'center'

    btn_txt: ''
    lbl_txt: ''

    BoxLayout:
        size_hint: None, 1
        width: 200
        orientation: 'horizontal'
        Button:
            text: root.btn_txt
        Label:
            text: root.lbl_txt


GridLayout:    # Root rule
    rows: 3

    Label:
        font_size: 25
        text: "Some Headline"

    GridLayout:
        rows: 2
        row_force_default: True
        row_default_height: 40

        MiddleSection:
            btn_txt: "Button 1"
            lbl_txt: "Label 1"

        MiddleSection:
            btn_txt: "Button 2"
            lbl_txt: "Label 2"


"""))

输出