Python | Relative Layout in Kivy

Python | Relative Layout in Kivy

In Kivy, a RelativeLayout allows you to place and size widgets relative to the layout's size or the position of other widgets within the same layout. Widgets positioned in a RelativeLayout are placed according to their pos_hint and sized according to their size_hint properties.

Here's an example of how to use a RelativeLayout in Kivy, which includes a Python script and a corresponding .kv file.

First, create the main Python file (main.py):

from kivy.app import App from kivy.uix.relativelayout import RelativeLayout class MyRelativeLayout(RelativeLayout): pass class RelativeLayoutApp(App): def build(self): return MyRelativeLayout() if __name__ == '__main__': RelativeLayoutApp().run() 

Next, create the Kivy file (relativelayoutapp.kv), making sure the name matches the App class name (minus 'App'):

<MyRelativeLayout>: Button: text: 'Top Left' size_hint: None, None size: 100, 50 pos_hint: {'top': 1, 'x': 0} Button: text: 'Top Right' size_hint: None, None size: 100, 50 pos_hint: {'top': 1, 'right': 1} Button: text: 'Bottom Right' size_hint: None, None size: 100, 50 pos_hint: {'y': 0, 'right': 1} Button: text: 'Bottom Left' size_hint: None, None size: 100, 50 pos_hint: {'y': 0, 'x': 0} Button: text: 'Center' size_hint: None, None size: 100, 50 pos_hint: {'center_x': .5, 'center_y': .5} 

In the .kv file:

  • We define a RelativeLayout subclass called MyRelativeLayout.
  • Inside it, we place five Button widgets at the top left, top right, bottom right, bottom left, and center positions within the layout using the pos_hint property.
  • We use size_hint: None, None to disable the automatic sizing behavior for these widgets, so we can manually set their sizes with size.

To run the app, execute the main.py script. You will see a window with five buttons positioned relative to the corners and center of the window. If you resize the window, you'll notice how the buttons maintain their positions relative to their defined locations (top, bottom, right, left, center_x, center_y).


More Tags

ivr ignore-case syntax rgb controls sample drupal-blocks ios-app-extension email-ext visibility

More Programming Guides

Other Guides

More Programming Examples