Search code examples
kivykivy-language

Kivy: Can you have a BoxLayout within an AnchorLayout?


Goal: simply have two buttons side by side in the top right of the screen.

Attempted Method: To use AnchorLayout to place a BoxLayout in the top right of the screen.

.kv file:

AnchorLayout:
    anchor_x: "right"
    anchor_y: "top"
    BoxLayout:
        orientation: 'horizontal'
        Button:
            text: "Button 1"
            size_hint: None, None
            size: 100, 100
        Button:
            text: "Button 2"
            size_hint: None, None
            size: 100,100

Result: This places the buttons on the bottom left of the screen, not the top right as intended.

Question: What's wrong with this, and what is best way to place a row of buttons anchored to the top right of the screen?


Solution

  • That is happening because the BoxLayout is getting set to the same size as the AnchorLayout, due to the default size_hint of (1,1). You can fix that by adding size_hint: None, None and size: self.minimum_size:

    AnchorLayout:
        anchor_x: "right"
        anchor_y: "top"
        BoxLayout:
            orientation: 'horizontal'
            size_hint: None, None
            size: self.minimum_size
            Button:
                text: "Button 1"
                size_hint: None, None
                size: 100, 100
            Button:
                text: "Button 2"
                size_hint: None, None
                size: 100,100