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()
['TIMESTAMP', 'TARGETS', 'MULTIPLE', 'SAVE_TARGETS', 'UTF8_STRING',
'COMPOUND_TEXT', 'TEXT', 'STRING', 'text/plain;charset=utf-8',
'text/plain']
>>> Clipboard.get('TEXT')
'Hello World'
>>> Clipboard.put('Great', 'UTF8_STRING')
>>> Clipboard.get_types()
['UTF8_STRING']
>>> Clipboard.get('UTF8_STRING')
'Great'

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()
textinput.bind(text=on_text)

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

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)
        Clipboard.put(textinput.text,'UTF8_STRING')
        button.text= Clipboard.get('UTF8_STRING')
        self.add_widget(button)
        
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
        textinput.bind(text=on_text)
        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')
        layout.add_widget(button)
        layout.add_widget(textinput)
        root.add_widget(layout)
        return root
      
if __name__ == '__main__':
    MyClipBoardApp().run()

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
bubble.add_widget(your_widget_instance)

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!

bubbledemo.py

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)
        layout.add_widget(my_btn)
        root.add_widget(layout)
        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
        my_bubble.add_widget(my_bub_btn1)
        my_bubble.add_widget(my_bub_btn2)
        my_bubble.add_widget(my_bub_btn3)
        self.add_widget(my_bubble)
        
      
if __name__ == '__main__':
    MyBubbleApp().run()

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

Output

bubble_demo_2

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')
tp.add_widget(th)
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!

tabbedpanel.py

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)

          tb_panel.add_widget(th_text_head)
          tb_panel.add_widget(th_img_head)
          tb_panel.add_widget(th_btn_head)          

          return tb_panel

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

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

kivy_tabbedpanel_2

kivy_tabbedpanel_3

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! 🙂

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
kivy.require('1.4.0')

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):
                Window.screenshot(name='screenshot%(counter)04d.jpg')
    
	      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(cam)

                button=Button(text='screenshot',size_hint=(0.12,0.12))
                button.bind(on_press=self.doscreenshot)
                camwidget.add_widget(button)    #Add button to Camera Widget
                
                return camwidget
            
if __name__ == '__main__':
    MyApp().run()                              

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
kivy.require('1.4.0')

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

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

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: