【问题标题】:Centering BoxLayout with Buttons inside a GridLayout使用 GridLayout 内的按钮将 BoxLayout 居中
【发布时间】:2019-09-06 16:53:55
【问题描述】:

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

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

这是我当前的 .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"

生成的窗口如下所示

但我想要的是这些带有按钮/标签的 BoxLayouts 在窗口中居中。

我怎样才能做到这一点或者我需要改变什么?

【问题讨论】:

    标签: python python-3.x kivy kivy-language


    【解决方案1】:

    Kivy AnchorLayoutanchor_x: 'center'anchor_y: 'center' 一起使用

    Kivy AnchorLayout » anchor_x

    anchor_x
    

    水平锚。

    anchor_x 是OptionProperty,默认为“中心”。它 接受“左”、“中”或“右”的值。

    Kivy AnchorLayout » anchor_y

    anchor_y
    

    垂直锚点。

    anchor_y 是OptionProperty,默认为“中心”。它 接受“top”、“center”或“bottom”的值。

    示例

    以下示例说明了 Kivy AnchorLayoutDynamic 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"
    
    
    """))
    

    输出

    【讨论】:

      猜你喜欢
      • 2016-03-11
      • 2012-10-14
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      相关资源
      最近更新 更多