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.

Example

from kivy.app 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))
      anchor1.add_widget(button1)
      # 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))
      anchor2.add_widget(button2)
      # Create a box layout
      BL = BoxLayout()
      # Add both the anchor layouts to the box layout
      BL.add_widget(anchor1)
      BL.add_widget(anchor2)
      # Return the boxlayout widget
      return BL
# Run the Kivy app
if __name__ == '__main__':
   AnchorLayoutApp().run()

Running the above code gives us the following result −

Output

Updated on: 28-Dec-2020

474 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements