Layouts

As mentioned in the previous section, layouts serve as containers for holding widgets and other layouts as well.In fact layouts are widgets as well. We will not mention all the layouts here, but we will work with the most important or most widely used ones that you will need. The following are some , if not all layouts of kivy: AnchorLayout,BoxLayout,FloatLayout,GridLayout,PageLayout,RelativeLayout,ScatterLayout and more. But the ones that are widely used are BoxLayout,GridLayout.For a list of all layouts, you can always refer to the kivy documentation.

BoxLayout

The BoxLayout places widgets on the screen either vertically, or horizontally.So you can say that a BoxLayout is either a vertical BoxLayout or a horizontal BoxLayout. Let us see a BoxLayout with three buttons.

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button


class RootWidget(BoxLayout):
    def __init__(self,**kwargs):
        super(RootWidget,self).__init__(**kwargs)
        self.orientation = 'horizontal'
        self.add_widget(Button(text='Button1'))
        self.add_widget(Button(text='Button2'))
        self.add_widget(Button(text='Button3'))



class MainApp(App):
    def build(self):
        return RootWidget()
if __name__ =="__main__":
    MainApp().run() 

This produces the following image

boxlayout

Explanation

The first few lines do the usual imports. And note that you must import anything that you need before you can use it. Previously, we returned just a button in the build method of our App class. But to have a layout with more widgets, in this case we create our own BoxLayout that we call RootWidget.It is not mandatory to call it RootWidget but you can give it the name you want. If you have done Object Oriented Python, the __init__ method should not be new to you. We call super() within init, and what that does it to call the __init__ method of our parent widget BoxLayout. As seen on the above image,the buttons are laid out from left to right and each occupies the same amount of space.This is done by the line

self.orientation = 'horizontal'

We told it to lay the children widgets from left to right.

Method add_widget()

Calling self.add_widget() simply means that we want a widget, in this case Buttons, to be added to the layout.You pass to add_widget() a widget instance.

Vertical BoxLayout

To have out buttons displayed vertically, just change the line

self.orientation = 'horizontal' 

to

self.orientation = 'vertical' 

You should now see the following image rendered

Vertical boxlayout

Important

Something that we forgot to mention in the previous section is that you must call App().run() before you can see your application displayed

GridLayouts

The GridLayout widget is a widget that arranges its children in grids. It has two important properties; cols and rows. You set cols when want a certain number of columns and rows when you want a certain number of rows. So if I have a gridlayout widget and I set the property self.cols = 3, the widget will be arranged in three columns. Enough of the talk. Let us see some code..

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout


class RootWidget(GridLayout):
    def __init__(self,**kwargs):
        super(RootWidget,self).__init__(**kwargs)
        self.cols = 3
        self.add_widget(Button(text='Button1'))
        self.add_widget(Button(text='Button2'))
        self.add_widget(Button(text='Button3'))
        self.add_widget(Button(text='Button4'))
        self.add_widget(Button(text='Button5'))
        self.add_widget(Button(text='Button6'))
        self.add_widget(Button(text='Button7'))
        self.add_widget(Button(text='Button8'))
        self.add_widget(Button(text='Button9'))

class MainApp(App):
    def build(self):
        return RootWidget()
if __name__ =="__main__":
    MainApp().run() 

This renders the following image

gridlayout

We set cols property to cols property to 3 and the layout knows what to do. When you add three children, the fourth will be added on the next row. Now go and change the line that reads

self.cols = 3

to

self.rows = 2

This forces the layout to have two rows of items. The image is shown below

Gridlayout with rows

Try adding more buttons to the layout. You will find out that the buttons will always be forced to two rows.

Up till now Only Buttons?

All we have been doing is play with buttons. Do not get bothered so soon. We will be seeing more widgets soon. Here, all I want to do is introduce you to make you know all the necessary layouts that you will encounter or need. In fact in the next section we will build our first meaningful app. I do not know what we will build yet but let's proceed with our layouts..

AnchorLayout

The anchorlayout is used when you want widgets placed on a particular location on the screen. It is controlled by the properties anchor_x and anchor_y. Setting anchor_x to left means that the widgets will be placed on the leftmost part of your layout. Other possible values for anchor_x are, center,and right. Property anchor_y controls where widgets are placed on the y-axis of your layout. Possible values for anchor_y are center,top,top. Let us see some sample code

from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button
from kivy.app import App

class Anchor(AnchorLayout):
    def __init__(self, **kwargs):
        super(Anchor,self).__init__(**kwargs)
        self.anchor_x = 'left'
        self.anchor_y = 'bottom'
        b1 = Button(text='B1',size_hint=(.4,.3))   
        b2 = Button(text='B2',size_hint=(.2,.3))    
        b3 = Button(text='B3',size_hint=(.2,.5))    
        b4 = Button(text='B4',size_hint=(.2,.2))  
        self.add_widget(b1)
        self.add_widget(b2)
        self.add_widget(b3)
        self.add_widget(b4)
class MainApp(App):
    def build(self):
        return Anchor()

if __name__ == '__main__':
    MainApp().run()

The image rendered follows

Anchorlayout

You will see the widgets stacked to the bottom left of the screen. Try altering the values for anchor_x and anchor_y to see the effect. The truth is I rarely use the AnchorLayout but it is good fo absolute positioning.

What is that new size_hint stuff?

If you have gone through the code, you will see a new thing, the size_hint on the buttons. The size_hint is a tuple or list. It sets the size for the width and height, the first being the width and the second being the height.

size_hint = (.2,.4)

means that we want the button to take 20% of the parent layout's width,Anchor and 40% of the height . If we did not specify the size_hint on the buttons, the only widget displayed will have been the widget added last, that is b4. More about size_hinting in the future..

More Layouts

I will leave the layouts stuff here. I will advise you to check the RelativeLayout and FloatLayout most importantly. You should also check others mentioned or not mentioned because we will use them in other parts.

What next?

Let us build our first app in the next section..