In this Python Kivy article we want to learn about How to Create a BoxLayout in Python Kivy, so Kivy is powerful and open source Python GUI Framework, and it is used for building multi touch applications, Kivy provides different layout managers, using these layout managers we can structure our application. one important layout is BoxLayout, which arrange widgets in a linear fashion.
First of all we need to install Kivy and we can use pip for the installation.
1 |
pip install kivy |
After installation, this is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label class MyBoxLayout(BoxLayout): def __init__(self): super().__init__() self.orientation = 'vertical' # Set the orientation to vertical self.add_widget(Label(text='Label 1')) self.add_widget(Label(text='Label 2')) self.add_widget(Label(text='Label 3')) class MyApp(App): def build(self): return MyBoxLayout() if __name__ == '__main__': MyApp().run() |
In the above code first we have imported the required modules.
1 2 3 |
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label |
After that we define a class that inherits from BoxLayout class. this class will represent our box layout. in our this class we want to define the structure and properties of our layout.
1 2 3 4 5 6 7 |
class MyBoxLayout(BoxLayout): def __init__(self): super().__init__() self.orientation = 'vertical' self.add_widget(Label(text='Geekscoders.com')) self.add_widget(Label(text='Geekscoders.com')) self.add_widget(Label(text='Geekscoders.com')) |
In the above code, we have created an instance of the MyBoxLayout class and set the orientation to vertical. after that we add three Label widgets to the box layout using the add_widget method.
Now, we need to create an App class to run our application. this class will be responsible for creating and running the user interface, in the build method, we instantiate our MyBoxLayout class and return it.
1 2 3 |
class MyApp(App): def build(self): return MyBoxLayout() |
For starting our application, we need to create an instance of the MyApp class and call its run method.
1 2 |
if __name__ == '__main__': MyApp().run() |
Run the complete code and this will be the result
