Anchor Layout In Kivy

Overview:

Kivy the open source Python library for developing applications has several layouts for the developer to choose from including Anchor Layout, BoxLayout, FloatLayout, RelativeLayout, GridLayout, PageLayout, ScatterLayout and StackLayout.

The anchor layout is a layout in which widgets are placed to one of the borders. The borders can be left, right, top, bottom and center. The class kivy.uix.anchorlayout.AnchorLayout implements the anchor layout.

AnchorLayout can be initialized with the parameters anchor_x and anchor_y to select which border of a parent container, the widgets are placed to.

The anchor_x parameter can be passed the values “left”, “right” and “center”.

The anchor_y parameter can be passed the values “top”, “bottom” and “center”.

In effect, a Kivy widget placed using the anchor layout is placed in any of the following layout regions: Top-left, top-center, top-right, center-left, center-center, center-right, bottom-left, bottom-center and bottom-right.

Remember adding multiple widgets to an anchor layout, only positions the widgets at the same location. In the example given here, two anchor layouts are created. The first anchor layout has its anchor at Bottom-Left and the second anchor layout has its anchor at Top-Right. Both of them are added with two buttons and the anchor-layouts themselves are added to a BoxLayout instance which is returned from the build() method of the App class.

 

Example:

# Sample Python application demonstrating the working of AnchorLayout in Kivy

 

# Module imports

from kivy.app import App

 

from kivy.uix.anchorlayout import AnchorLayout

from kivy.uix.boxlayout import BoxLayout

from kivy.uix.button import Button

 

from kivy.graphics import Color, Rectangle

 

# A Kivy app demonstrating the working of anchor layout

class AnchorLayoutDemo(App):

    def build(self):

        # Anchor Layout1

        anchorLayout1       = AnchorLayout(anchor_x='left', anchor_y='bottom')

        button1             = Button(text='Bottom-Left', size_hint = (0.3, 0.3))

        anchorLayout1.add_widget(button1)

       

        # Anchor Layout2

        anchorLayout2    = AnchorLayout()

        anchorLayout2.anchor_x = 'right'

        anchorLayout2.anchor_y = 'top'

       

        # Add the anchor layouts to a box layout    

        button2 = Button(text='Top-Right', size_hint = (0.3, 0.3))

        anchorLayout2.add_widget(button2)

       

        # Create a box layout

        boxLayout = BoxLayout()

 

        # Add both the anchor layouts to the box layout

        boxLayout.add_widget(anchorLayout1)

        boxLayout.add_widget(anchorLayout2)

 

        # Return the boxlayout widget

        return boxLayout

 

# Run the Kivy app

if __name__ == '__main__':

    AnchorLayoutDemo().run()

 

Output:

Anchor layout in kivy


Copyright 2023 © pythontic.com