Box Layout In Kivy With Example

Overview:

  • Kivy offers several layouts to keep widgets in their designated places on an application. BoxLayout is a simple yet powerful layout often used either in a nested way or in a simple plain way.
  • BoxLayout arranges widgets in either in vertical fashion that is one on top of another or in horizontal fashion that is one after another.
  • When no size-hint is used, the size of the parent widget is equally divided and given to the child widgets. The size here is width or height depending on the orientation of the box layout.
  • BoxLayout is like storing the boxes one above another or one next to another, but not both the schemes in a single layout instance.
  • Each of the widgets contained can have the size_hint specified for them.
  • size_hint works in such a way that the widgets are allocated a fraction of the size of the parent in x or y direction.

Example:

# Sample Kivy app demonstrating the working of Box layout

 

# imports

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.uix.button import Button

 

# Boxlayout is the App class

class BoxLayoutDemo(App):

    def build(self):

        superBox        = BoxLayout(orientation='vertical')

   

        horizontalBox   = BoxLayout(orientation='horizontal')

        button1         = Button(text="One")

        button2         = Button(text="Two")

 

        horizontalBox.add_widget(button1)

        horizontalBox.add_widget(button2)

   

        verticalBox     = BoxLayout(orientation='vertical')

        button3         = Button(text="Three")

        button4         = Button(text="Four")

 

        verticalBox.add_widget(button3)

        verticalBox.add_widget(button4)

   

        superBox.add_widget(horizontalBox)

        superBox.add_widget(verticalBox)

   

        return superBox

   

 

# Instantiate and run the kivy app

if __name__ == '__main__':

    BoxLayoutDemo().run()

 

Output:

Box layout in Kivy


Copyright 2023 © pythontic.com