Learning Kivy: Clipboard and Text Input

Hey everyone!

It’s time for another cool Kivy tutorial. In this one I will explain how to use the Clipboard core module to copy text from a Text Input widget. The text thus copied will be applied to a Button, displayed in our layout.

Kivy provides a core class for accessing the Clipboard. It is used mainly to copy some data so that it can be used somewhere else. On the other hand, the Text Input widget provides a box of editable plain text. At present it supports unicode, multi line, cursor navigation, selection and clipboard features.

Usage of Clipboard:

>>> from kivy.core.clipboard import Clipboard
>>> Clipboard.get_types()
'COMPOUND_TEXT', 'TEXT', 'STRING', 'text/plain;charset=utf-8',
>>> Clipboard.get('TEXT')
'Hello World'
>>> Clipboard.put('Great', 'UTF8_STRING')
>>> Clipboard.get_types()
>>> Clipboard.get('UTF8_STRING')

Usage of Text Input:

To create a multiline textinput (‘enter’ key adds a new line):

from kivy.uix.textinput import TextInput
textinput = TextInput(text='Hello world')

The textinput’s text is stored on its TextInput.text property. To run a callback when the text changes:

def on_text(instance, value):
    print('The widget', instance, 'have:', value)

textinput = TextInput()

Now, let’s write a small program that will dynamically copy the value from the Text Input widget and apply it as text to a Button using the Kivy Clipboard!

Open Python IDLE and create a new Python script named clipboard.py


from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.core.clipboard import Clipboard
from kivy.uix.button import Button

button = Button(pos=(300,300),font_size=20)
textinput= TextInput(text='Hello world',multiline=False)
def on_text(self, *args):
        print ('new value is ', textinput.text)
        button.text= Clipboard.get('UTF8_STRING')
class MyClipBoardApp(App):
    def build(self):
        root= GridLayout()
        layout = FloatLayout(orientation='horizontal', size=(450,300), size_hint=(None, None))
        #call function when text changes inside TextInput
        print ('value is ', textinput.text)
        print Clipboard.put(textinput.text,'UTF8_STRING')
        print Clipboard.get('UTF8_STRING')
        #Use copied clipboard value as text for Button
        button.text= Clipboard.get('UTF8_STRING')
        return root
if __name__ == '__main__':

Run the above code by typing kivy clipboard.py inside command prompt. You should see the following output!

before text changed

before text changed

after text changed

after text changed

Source code for this example can also be found over here

Learning Kivy: Bubble

Hello friends!

Today, we will learn about a very simple yet fascinating Kivy widget called Bubble. The Bubble widget is basically a small pop up that appears and consists of menu options that are stacked either horizontally or vertically.

Every Bubble widget contains an arrow pointing towards the direction you choose. By default the direction is ‘bottom_mid’ i.e bottom middle.

A Bubble widget can be implemented as:

bubble = Bubble(orientation = 'vertical')
#Add items to the Bubble

What is a BubbleButton?

It is basically a button intended for use as in a Bubble widget. Using BubbleButton you can use the background that has been already defined. On the other hand if you stick to Bubble then you need to customize it in order to change the background image, color etc.

Customizing your bubble

You can change the background color, image and border of the Bubble. You can also add an image for the arrow as follows:

bubble.background_color = (1, 0, 0, .5) #50% translucent red
bubble.border = [0, 0, 0, 0]
background_image = 'path/to/background/image'
arrow_image = 'path/to/arrow/image'

So now let’s begin implementing the Bubble widget!

Open Python IDLE. Create a new Python script named bubbledemo.py and write the following code!


from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.bubble import Bubble
from kivy.uix.bubble import BubbleButton

class MyBubbleApp(App):
    def build(self):
        root= GridLayout()
        layout = FloatLayout(orientation='horizontal', size=(150,100), size_hint=(None, None))
        my_btn=Button(text='Press to view bubble',pos=(300,300),on_press=show_bubble)
        return root

def show_bubble(self,*args):
        my_bubble= Bubble(orientation = 'horizontal',pos=(280,400))
        #Customizing my bubble
        my_bubble.background_color =(20, 0, 0, .5) 
        my_bubble.border = [50, 50, 50, 10]
        my_bubble.arrow_pos= 'top_left'
        my_bub_btn1= BubbleButton(text='Copy',size_hint=(None, None),size=(80, 50),pos=(200,400)) 
        my_bub_btn2= BubbleButton(text='Cut',size_hint=(None, None),size=(80, 50),pos=(300,400))
        my_bub_btn3= BubbleButton(text='Paste',size_hint=(None, None),size=(80, 50),pos=(300,400))
        #Add items to bubble
if __name__ == '__main__':

Run the above script by typing kivy bubbledemo.py inside the command prompt and you should see the following output!



Learning Kivy: TabbedPanel

Hello everyone!

On May 13th, 2013 Kivy launched version 1.7.0 for it’s platform. The new version includes some cool features as well. You can have a look at the changelog from over here.

Today’s Kivy tutorial talks about one of the existing complex UX widgets called TabbedPanel. The TabbedPanel widget manages different widgets in tabs. It consists of a header area for the actual tab buttons and a content area for showing the current tab content. Before you begin implementing this widget you need to understand the concept of a TabbedPanelHeader.

What is a TabbedPanelHeader?

An individual tab is called a TabbedPanelHeader. It is a special button containing the content property. In order to use it, we need to first add the TabbedPanelHeader to our TabbedPanel and then set its content as seen below!

tp = TabbedPanel()
th = TabbedPanelHeader(text='Tab2')
th.content = your_content_instance

Once you are clear with the concept of a TabbedPanelHeader, you can now go ahead and start implementing your own TabbedPanel widget. Fire up Python IDLE and begin writing the following code!


from kivy.app import App
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.tabbedpanel import TabbedPanelHeader
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.image import Image

class TabbedPanelApp(App):
      def build(self):
          tb_panel= TabbedPanel()

          #Create text tab          
          th_text_head = TabbedPanelHeader(text='Text tab')
          th_text_head.content= Label(text='This is my text content')

          #Create image tab
          th_img_head= TabbedPanelHeader(text='Image tab')
          th_img_head.content= Image(source='sample.jpg',pos=(400, 100), size=(400, 400))

          #Create button tab
          th_btn_head = TabbedPanelHeader(text='Button tab')
          th_btn_head.content= Button(text='This is my button',font_size=20)


          return tb_panel

if __name__ == '__main__':

Run the above code using Kivy by typing kivy tabbedpanel.py inside the command prompt. You should get the following output!



Output screenshots

Output screenshots

It is important to note that the Default tab is added when the TabbedPanel is instantiated. Tabs created individually get added to the Default tab.

So, that’s it for this tutorial. Keep visiting for some more interesting Kivy tutorials! :)

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.


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:
1. One container for the title bar
2. 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.

Accordion output



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 tutorial. Hope it helps you in some way! Thanks :)

Learning Kivy: Canvas

Hey everyone!

In my previous Kivy tutorial I talked about the Carousel widget and the AsyncImage class that one can use to display and load images respectively. Today I would be talking about the Graphics module of the Kivy framework!

1. Graphics (kivy.graphics)

From the Kivy documentation, the Graphics package assembles all low level functions to draw an object.The entire package is compatible with OpenGL ES 2.0 and has a lot of rendering optimizations.

There are basically two things that one would require to draw on a screen. They are namely:

1. Canvas
2. Instruction objects

Each widget in Kivy already have their Canvas by default. When you are creating a widget, you can create all the instructions needed for drawing. If self is your current widget, you can do:

from kivy.graphics import *
with self.canvas:
    # Add a red color
    Color(1., 0, 0)

    # Add a rectangle
    Rectangle(pos=(10, 10), size=(500, 500))

The instructions Color and Rectangle are automatically added to the canvas object, and will be used when the window drawing will happen.

2. Canvas (kivy.graphics.instructions)

The Canvas is a root object used for drawing by a Widget. The Canvas supports Python’s with statement and it’s enter and exit semantics.

Use of Canvas without the with statement

self.canvas.add(Color(1., 1., 0))
self.canvas.add(Rectangle(size=(50, 50)))

Usage of Canvas with Python’s with statement

with self.canvas:
    Color(1., 1., 0)
    Rectangle(size=(50, 50))

Now, here’s a small implementation of the Canvas object!

Open Python IDLE and create a new Python script. Give the name as canvas_demo.py

from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.graphics import Color, Rectangle
from functools import partial

class CanvasApp(App):

    #function to add rectangle to screen
    def add_rects(self,wid,*largs):
        with wid.canvas:
                Color(1, 0, 0, .5, mode='rgba')
                wid.rect = Rectangle(pos=(200,200), size=(300,300))
    #function to clear rectangle from screen
    def reset_rects(self,wid,*largs):

    def build(self):
        wid = Widget()
        #calling function with default arguments
        btn_add = Button(text='Draw rectangle',on_press=partial(self.add_rects,wid,'Adding a rectangle'))
        btn_clear = Button(text='Clear',on_press=partial(self.reset_rects,wid,'Clear the canvas'))

        layout = GridLayout(cols=1,rows=2)

        return root

if __name__ == '__main__':

On running the above code, you should see a red color rectangle as soon as you click on the Draw Rectangle button. On pressing the Clear button the rectangle will disappear!



Learning Kivy: Carousel and AsyncImage

Hello everyone!

Today I will talk about two interesting Widgets of the Kivy framework. Both these widgets can be used to display/load images in a particular manner.

1. Carousel

As mentioned in the Kivy docs, the Carousel widget provides a mobile-friendly carousel view where one can swipe between slides. One can add any content to the carousel and use it horizontally or vertically. The carousel can display pages in loop. One can also navigate to the next slide or the previous slide using the Carousel properties.

Here’s how we can use the Carousel view!

Step 1: Create a folder named images on your disk and copy a few pictures inside that folder. I have added a few images for my project. Download the source code from the below link to view them.

Step 2: Open the Python IDLE. Create a new Python script and type the following code!

from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.factory import Factory
from kivy.uix.image import Image

class Example1(App):

    def build(self):
        #define the carousel
        carousel = Carousel(direction='right',loop='true')
        for i in range(1,5):
            #load pictures from images folder
            src = "images/%d.jpg" % i
            image = Image(source=src,pos=(400, 100), size=(400, 400))
        return carousel

if __name__ == '__main__':

Step 3: Save the file as Example1.py. Make sure to save the Python file inside the same directory as that of the images folder.

Step 4: Open command prompt. Navigate to the directory where you have your Python script. Type kivy Example1.py and press enter. You should get a carousel view of various fruit images!

Kivy Carousel View

Kivy Carousel View

Here is the Source code

2. AsyncImage

Now, the AsyncImage class is used to load images asynchronously from an external webserver. All one needs to do is specify the URL of the website that contains the data. One can use AsyncImage in combination with Carousel to load and display images.

Here’s a short implementation of the AsyncImage class along with the Carousel view.

Once again create a new Python script. Add the following code. Run it as explained previously and you should see some images getting loaded asynchronously!

from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.factory import Factory
from kivy.uix.image import Image

class Example1(App):

    def build(self):
        carousel = Carousel(direction='right',loop='true')
        for i in range(1,5):
            src = "http://placehold.it/480x270.png&text=slide-%d&.png" % i
            #load images asynchronously
            image = Factory.AsyncImage(source=src, allow_stretch=True)
        return carousel

if __name__ == '__main__':

So that’s it for this tutorial. I will talk about the Graphics module of the Kivy framework in my further tutorials! Enjoy! :)

Learning Kivy: Animate widgets

Hello everyone!

The Kivy framework provides the kivy.animation module to animate widgets. For any animation, we must specify certain values that represent the position of the animated object.

To use Animation in Kivy one needs to follow two simple steps namely:

1. Setup an Animation object
2. Use the Animation object on a Widget

There are two kinds of Animation that can be applied:

1. Sequential Animation

As the name suggests, it is used to join animations sequentially using the ‘+’ operator.

Example from Kivy docs:

anim = Animation(x=50) + Animation(size=(80, 80), duration=2.)

The above example will animate to x=50 over 1 second, then animate size to (80, 80) over the next two seconds.

2. Parallel Animation

It is used join animations in parallel. It uses the ‘&’ operator.

Example from Kivy docs:

anim = Animation(pos=(80, 10))
anim &= Animation(size=(800, 800), duration=2.)

The above example will animate position to (80, 10) over 1 second, while in parallel animating the first half of size=(800, 800).

Along with animations one can also use various Animation Transition properties to create custom animations for widgets. One can use built-in or custom transition functions using transition (or t= shortcut).

For example using the ‘in_quad’ transition as follows:

anim = Animation(x=50, size=(80, 80), t='in_quad')

Here is a sample program to demonstrate the Animation module in Kivy:

import kivy

from kivy.app import App
from kivy.uix.button import Button
from kivy.animation import Animation
from kivy.uix.widget import Widget

class MyAnimApp(App):

        def build(self):
            parent= Widget()
            button= Button(text='Animated', font_size=14)
            return parent
        def on_button_press(self,instance):
            anim = Animation(x=50, size=(50, 50), t='in_out_bounce')
            #apply sequential animation
            anim += Animation(pos=(200,70),t='in_out_back')
            #apply parallel animation
            anim &= Animation(size=(100,50))

if __name__== '__main__':

You can write the above code using the Python IDLE and run it as:

kivy yourfilename.py

Learning Kivy: Video Player and Scatter widgets

Hello everyone!

Today I would like to share with you something new that I learnt recently while working on the Kivy library. It includes a brief introduction about the Widget class in Kivy along with two sample programs that demonstrate complex UX widgets and behaviors widgets respectively.

Widget class is the base class required to create a Widget. We can add, position and clear widgets using the methods provided by the Widget API. In simpler terms, a widget is defined as an element of a graphical user interface.

Kivy includes various widgets such as:

1) Label, Button, CheckBox, Image, Progress Bar etc (called UX widgets)

2) Scatter, Stencil View (called Behaviors widgets)

3) Drop-Down List, FileChooser, Popup, Spinner, TabbedPanel, Video player etc (called Complex UX widgets)

4) Screen Manager widget

5) Grid Layout, Box Layout, Anchor Layout etc (called Layout widgets)

In this post I will talk about the Video Player and Scatter widgets.

Video Player widget:

As defined in the Kivy docs, “a Video Player widget can be used to play video and let the user control the play/pause, volume and seek. The widget cannot be customized much, because of the complex assembly of numerous base widgets”.

Here is a sample program that demonstrates the working of the Video Player widget:

Step 1: I will be using the softboy.avi video included in the Kivy samples for this purpose. You can also download a short video (.avi , .mkv) and use it. In order to display text at a specific time and duration of the video we can use annotations. An annotation file has a .jsa extension. You can find more information on annotations over here.

Step 2: You can open any editor like Notepad++ to write the code. I will be using the Python IDLE for now.

import kivy

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.videoplayer import VideoPlayer
parent= Widget()
button= Button()
class MyApp(App):
    def build(self):
         button = Button(text='Play video', font_size=14)
         parent.add_widget(button) #add button 
         return parent
def on_button_press(self):
        video= VideoPlayer(source='softboy.avi', state='play')
        parent.add_widget(video) #add videoplayer
        return parent
if __name__ == '__main__':

Step 3: Save this script as videoplayerdemo.py

Note: Make sure you have the video file (.avi), annotation file (.jsa) if any and your Python file (.py) in the same folder. Run the application from the command prompt by typing:

kivy videoplayerdemo.py

Click on the button “Play video” to start the video. Double click on the video to increase it’s size.

VideoPlayer widget snapshot 1

VideoPlayer widget snapshot 2

Scatter widget

The Scatter is a very simple widget to understand. It is basically used to build interactive widgets that can be translated, rotated and scaled with two or more fingers on a multitouch system. It acts as a container and is combined with other widgets.

Create a new Python script named scatterdemo.py and write the following code:

import kivy

from kivy.app import App
from kivy.uix.scatter import Scatter
from kivy.uix.image import Image    

class MyApp(App):
    def build(self):
         scatter= Scatter()
         # store kivy.jpg image in same folder as the python script
         image= Image(source='kivy.jpg')
         scatter.add_widget(image) #combine image widget with scatter
         return scatter
if __name__ == '__main__':

Run the application as done before and you will see an image of the Kivy logo. You can try dragging, rotating the image using the mouse.

Drag image

Rotate image

So that completes a quick look at some of the widgets in Kivy. There is still lots to learn and many more things to do! Have a great day! :)

Tutorial #6: Working with Camera in Kivy

Hey everyone, here is a new post that demonstrates the use of the Camera module in Kivy.

For those who are new to Kivy, I suggest you read the Getting started tutorial for Kivy before proceeding.

This tutorial describes the use of Camera, how to open a camera and take a screenshot of the live stream.

So let’s get started. Open your editor. I prefer Python IDLE. You can also choose any other editor.

Step 1: First you need to make sure that Kivy is up and running on your system. Go to the command prompt and type kivy and hit enter.

Step 2 : Create a new Python file named testcamera.py

Step 3: testcamera.py

import kivy

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.camera import Camera
from kivy.uix.button import Button
from kivy.core.window import Window

class MyApp(App):
          # Function to take a screenshot
          def doscreenshot(self,*largs):
	      def build(self):
                camwidget = Widget()  #Create a camera Widget
                cam = Camera()        #Get the camera
                cam=Camera(resolution=(640,480), size=(500,500))
                cam.play=True         #Start the camera

                camwidget.add_widget(button)    #Add button to Camera Widget
                return camwidget
if __name__ == '__main__':

Save your file. To run the program , go to the command prompt once again and type:

kivy testcamera.py

You should get a live stream. Click on the Screenshot button to take a snap.

For more information refer the Kivy docs for Camera, Window and Button

Getting started with Kivy

Kivy is a popular cross platform open source library for developing applications involving different user interfaces. Currently, Kivy is running on Linux, Windows, MacOSX, Android and iOS.

Let’s start by downloading Kivy for Windows from here : Kivy for Windows.

Unzip the downloaded file to find the kivy.bat file shown below:

Copy the path to this folder.

Now right click My Computer -> Properties -> Advanced System Settings -> Environment Variables

Select Path under System variables and click on Edit. Add the path you copied at the end of the Variable Value entry followed by a semicolon(;)

Open up a command prompt and type kivy to see whether kivy has be set up properly. You should see a message saying “done bootstrapping kivy..”

That completes the Kivy installation for Windows. Now moving on, let’s try a simple program.

Open any editor such as Notepad++ or best you can use the Python IDLE that comes along with a standard Python installation.

Write the following code:

import kivy

from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.widget import Widget

class ShowImage(Image):
class MyApp(App):
	  def build(self):
		    return ShowImage(source='tech2.jpg',pos=(30, 130),size=(256, 256))
if __name__ == '__main__':

Save the above file as imagedemo.py. The above code is used to display an Image using Kivy. ‘tech2.jpg’ is the name of the image file. Note that the image file and the imagedemo.py file should be placed inside the same folder.

Now switch to command prompt once again, navigate to the folder contain the python file and type the command –> kivy imagedemo.py

You should see a screen with an image as below: