In Kivy, the BoxLayout
class is used to arrange widgets in either a horizontal or vertical layout. It provides a simple way to organize your UI elements in a linear fashion.
To use the BoxLayout
class, you first need to import it from the kivy.uix
module:
from kivy.uix.boxlayout import BoxLayout
Next, create an instance of the BoxLayout
class and add your widgets to it. The BoxLayout
can be created with the parameter orientation
set to either “horizontal” or “vertical”:
layout = BoxLayout(orientation='horizontal')
Adding Widgets
To add widgets to the BoxLayout
, use the add_widget()
method. This method adds the widgets to the end of the layout, preserving their order:
layout.add_widget(widget1)
layout.add_widget(widget2)
layout.add_widget(widget3)
Widget Alignment
By default, the BoxLayout
centers its children widgets along the main axis. You can adjust the alignment using the alignment
property. The alignment
property accepts values like “left”, “right”, “top”, “bottom”, “center”, “justify”, etc.
layout.alignment = 'center'
Spacing
The BoxLayout
also allows you to control the spacing between its children widgets using the spacing
property. The spacing
property specifies the number of pixels between widgets.
layout.spacing = 10
Example
Here’s a simple example that demonstrates the usage of BoxLayout
:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
class MyBoxLayout(App):
def build(self):
layout = BoxLayout(orientation='horizontal', spacing=10)
button1 = Button(text='Button 1')
button2 = Button(text='Button 2')
button3 = Button(text='Button 3')
layout.add_widget(button1)
layout.add_widget(button2)
layout.add_widget(button3)
return layout
if __name__ == '__main__':
MyBoxLayout().run()
In this example, we create a simple App
with a BoxLayout
containing three buttons. The BoxLayout
is set to a horizontal orientation and each button has a spacing of 10 pixels between them.
The BoxLayout
is a powerful layout manager that helps you create clean and organized UIs in Kivy. Experiment with different orientations, alignments, and spacings to achieve the desired layout for your application.