Search code examples
pythonpython-3.xkivykivy-language

Centering BoxLayout with Buttons inside a GridLayout


I'm working with kivy for a new project. While designing my GUI, I encountered the following problem.

I have a GridView dividing my window in three section. The top sections contains a headline, and the middle section should contain centered Buttons and Labels.

This is my current .kv file:

<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"

The resulting window looks like this

But what I want instead is that these BoxLayouts with the Bottons/Labels are centered in the window.

How can I accomplish this or what do I have to change?


Solution

  • Use Kivy AnchorLayout with anchor_x: 'center' and 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’.

    Example

    The following example illustrates use of 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"
    
    
    """))
    

    Output

    Result