Python - AnchorLayout in Kivy

Kivy is an open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. It is used to develop the Android application, as well as Desktops applications. In this article we will see how to use the anchor layout positioning.

Using AnchorLayouts we place the widgets at one of the borders. The class kivy.uix.anchorlayout.AnchorLayout implements the anchor layout. Both the anchor_x parameter and anchor_y parameter can be passed the values ‘left’, ‘right’ and ‘center’. In the below program we create two buttons, attach them to two anchors and keep them in a BoxLayout.


from import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
class AnchorLayoutApp(App):
   def build(self):
      # Anchor Layout1
      anchor1 = AnchorLayout(anchor_x='left', anchor_y='bottom')
      button1 = Button(text='Bottom-Left', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0))
      # Anchor Layout2
      anchor2 = AnchorLayout(anchor_x='right', anchor_y='top')
      # Add anchor layouts to a box layout
      button2 = Button(text='Top-Right', size_hint=(0.3, 0.3),background_color=(1.0, 0.0, 0.0, 1.0))
      # Create a box layout
      BL = BoxLayout()
      # Add both the anchor layouts to the box layout
      # Return the boxlayout widget
      return BL
# Run the Kivy app
if __name__ == '__main__':

Running the above code gives us the following result −