Learning Kivy : Accordion

Hey everyone!

Working on Kivy has been an amazing learning experience. Kivy has made user interface development a lot easier. Today, I will talk about Accordion, one of the interesting widgets that Kivy has to offer to developers out there.

What is an Accordion ?

Accordion is basically a Widget in the form of a menu where in the options are stacked either horizontally or vertically. An Accordion will contain one or many AccordionItem instances such that each item when touched opens up displaying it's underlying content.

The current implementation divides the AccordionItem into two parts:

  • One container for the title bar
  • One container for the content

The title bar is made from a Kv template. In order to customize the title bar you need to design your own template.

The current default template is present in the kivy/data/style.kv file.

Here is a small implementation of the code required to build your own template that I found in the Kivy docs.

    text: ctx.title
            rgb: 1, 1, 1
                ctx.item.background_normal \
                if ctx.item.collapse \
                else ctx.item.background_selected
            pos: self.pos
            size: self.size
            xy: self.center_x, self.center_y
            angle: 90 if ctx.item.orientation == 'horizontal' else 0
            axis: 0, 0, 1
            xy: -self.center_x, -self.center_y

Now, let's start creating a simple Kivy app that displays an Accordion widget. Open Python IDLE. Create a new file named Accordion.py and start writing the following code!

In this example, I will be displaying images as my content when the user touches an item. For each item a different image would exist!


from kivy.uix.accordion import Accordion, AccordionItem
from kivy.uix.image import Image
from kivy.app import App

class SampleAccorApp(App):
    def build(self):
        # you can change orientation to horizontal as well
        root = Accordion(orientation='vertical')
        for x in xrange(5):
            item= AccordionItem(title='Image %d' %x)
            src = "images/%d.jpg" % x
            image = Image(source=src,pos=(400, 100), size=(400, 400))
            # add image to AccordionItem
        return root

if __name__ == '__main__':

Run the above code by writing kivy Accordion.py inside command prompt.



As compared to Accordion, the AccordionItem is more configurable and customizable. For example, you can set your own title background when the item is collapsed or opened.

    item = AccordionItem(background_normal='image_when_collapsed.png',

So, that's it for this post. Hope it helps you in some way! Thanks 😄