Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

THREADS OF LIFE

(HTTP://KARANBALKAR.COM/)
S T A R T PA US E R UN BUT NE VE R S T OP!!!

HO ME (HT T P ://K A R A NB A LK A R .C O M/)

A B O UT (HT T P ://K A R A NB A LK A R .C O M/A B O UT /)

C O NT A C T (HT T P ://K A R A NB A LK A R .C O M/C O NT A C T /)

FA Q (HT T P ://K A R A NB A LK A R .C O M/FA Q /)

NEW S (HT T P ://K A R A NB A LK A R .C O M/NEW S /)

Tag Archives: kivy

Learning Kivy: Clipboard


and Text Input
(http://karanbalkar.com/2
013/06/learning-kivyclipboard-and-text-input/)
Posted on JUNE 8 , 2 0 1 3
(HT T P:/ / KA R A NBA LKA R .COM/ 2 0 1 3 / 0 6 / LE A R NINGKIVY-CLIPBOA R D-A ND-T E XT -INPUT / ) by KA R A N
BA LKA R
(HT T P:/ / KA R A NBA LKA R .COM/ A UT HOR / KA R A NBA LK
AR/)

Hey everyone!
Its 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
(http://kivy.org/docs/api-kivy.uix.button.html),
displayed in our layout.

(http://feeds.feedbur
ner.com/karanbalkar)
Feed
(http://karanbalkar.co
m/)
Using Proximity
sensor in Android
(http://feedproxy.goog
le.com/~r/karanbalkar
/~3/pywJtsUtqc0/)
Whats seen through
[Glass]
(http://feedproxy.goog
le.com/~r/karanbalkar
/~3/2Gx4v2G5IPk/)
Display static Google
Maps in Android
(http://feedproxy.goog
le.com/~r/karanbalkar
/~3/jYgliX41RS0/)

Subscribe via Email

Kivy provides a core class for accessing the


Clipboard
(http://kivy.org/docs/apikivy.core.clipboard.html). It is used mainly to copy
some data so that it can be used somewhere else.

Enter your email address


to subscribe to this blog
and receive notifications
of new posts by email.
Join 74 other subscribers

On

EmailAddress

the

other

hand,

the

Text

Input

On
the
other
hand,
the
Text
Input
(http://kivy.org/docs/api-kivy.uix.textinput.html)
widget provides a box of editable plain text. At
present it supports unicode, multi line, cursor
navigation, selection and clipboard features.

EmailAddress
Subscribe

Join me on Facebook

Usage of Clipboard:
ThreadsOfLifebyKaran
Balkar
>>> from kivy.core.clipboard import Clipboard
>>> Clipboard.get_types()
Megusta
['TIMESTAMP', 'TARGETS', 'MULTIPLE', 'SAVE_TARGETS'
'COMPOUND_TEXT', 'TEXT', 'STRING', 'text/plain;charset=utf-8'
A188personaslesgustaThreadsOfLifeby
'text/plain']
KaranBalkar.
>>> 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 textinputs 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, lets 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
def on_text(self, *args):

PluginsocialdeFacebook

Favorite Links
Android Developers
Blog (http://androiddevelopers.blogspot.in
/)
Another Stupid Coder's
Blog
(http://srivatsaniyer.bl
ogspot.in/)
Coding Horror
(http://www.codinghor
ror.com/blog/)
Experience The
Creativity
(http://sarangasl.blogs
pot.in/)
Manas Gajare's Blog
(http://manasgajare.c
om/)
The Global Panorama
(http://theglobalpanor
ama.com/)

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)

Blog Stats
Visits today: 1359

class MyClipBoardApp(App):
def build(self):
root= GridLayout()
layout = FloatLayout(orientation='horizontal'
Recent
Posts
#call function when text changes inside TextInp
ut
textinput.bind(text=on_text)
print ('value is ', textinput.text)
Using Proximity
print Clipboard.put(textinput.text,'UTF8_STRING'sensor in Android
print Clipboard.get('UTF8_STRING')
#Use copied clipboard value as text for Button (http://karanbalkar.co
m/2014/07/usingbutton.text= Clipboard.get('UTF8_STRING'
layout.add_widget(button)
proximity-sensor-inlayout.add_widget(textinput)
android/)
root.add_widget(layout)
return root
Whats seen through
if __name__ == '__main__':
MyClipBoardApp().run()

Run the above code by typing kivy clipboard.py


inside command prompt. You should see the
following output!

[Glass]
(http://karanbalkar.co
m/2014/07/whatsseen-through-glass/)
Display static Google
Maps in Android
(http://karanbalkar.co
m/2014/07/displaystatic-google-maps-inandroid/)
Using JSoup in Android
(http://karanbalkar.co
m/2014/06/usingjsoup-in-android/)

(http://karanbalkar.com/2013/06/learningkivy-clipboard-and-textinput/before_text_changed/)
before text changed

Populate Highcharts
with JSON data using
jQuery
(http://karanbalkar.co
m/2014/06/populatehighcharts-with-jsondata-using-jquery/)

Recent Comments
KeyEvent.KEYCODE_MI
NUS funktioniert nicht
- Android-Hilfe.de
(http://www.androidhilfe.de/android-appentwicklung/577059keyeventkeycode_minusfunktioniertnicht.html#post771151
7) on Tutorial #11:

7) on Tutorial #11:
Using TextWatcher in
Android
(http://karanbalkar.co
m/2012/10/tutorial11-using-textwatcherin-android/#comment1816)

(http://karanbalkar.com/2013/06/learningkivy-clipboard-and-textinput/after_text_changed/)
after text changed

Source code for this example can also be found


over
here
(https://github.com/karanbalkar/KivyClipBoardTextI
nputDemo)
Posted in Tech (http://karanbalkar.com/category/tech/) |
Tagged clipboard (http://karanbalkar.com/tag/clipboard/),
kivy (http://karanbalkar.com/tag/kivy/), python
(http://karanbalkar.com/tag/python/), text input
(http://karanbalkar.com/tag/text-input/) | 2 Comments
(http://karanbalkar.com/2013/06/learning-kivy-clipboardand-text-input/#comments) |

Learning Kivy: Bubble


(http://karanbalkar.com/2
013/05/learning-kivybubble/)
Posted on MA Y 2 7 , 2 0 1 3
(HT T P:/ / KA R A NBA LKA R .COM/ 2 0 1 3 / 0 5 / LE A R NINGKIVY-BUBBLE / ) by KA R A N BA LKA R
(HT T P:/ / KA R A NBA LKA R .COM/ A UT HOR / KA R A NBA LK
AR/)

Hello friends!
Today, we will learn about a very simple yet
fascinating Kivy widget called Bubble. The Bubble
(http://kivy.org/docs/api-kivy.uix.bubble.html)
widget is basically a small pop up that appears and
consists of menu options that are stacked either
horizontally or vertically.

linkedin-j 401 for URL:


https://api.linkedin.co
m/uas/oauth/requestT
oken - Tech Forum
Network
(http://techforumnetw
ork.com/techqns/linke
din-j-401-for-urlhttpsapi-linkedincomuasoauthrequestto
ken/) on Tutorial #57:
Connect to LinkedIn
using Java and OAuth
(http://karanbalkar.co
m/2013/09/tutorial57-connect-tolinkedin-using-javaand-oauth/#comment1721)
cheap sunglasses for
men
(http://fakeoakleysung
lasses.cc/cheapsunglasses-for-men/)
on Getting started with
COBOL!
(http://karanbalkar.co
m/2013/03/gettingstarted-withcobol/#comment1708)
Tutorial #34: Using
Google Maps Android
API v2 - appgong
(http://appgong.com/1
671/) on Tutorial #34:
Using Google Maps
Android API v2
(http://karanbalkar.co
m/2013/06/tutorial34-using-googlemaps-android-apiv2/#comment-1695)
Android notification
message at a
particular time
repeated every time

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:

repeated every time


the app launched |
questions android
(http://questionsandroid.buycity.info/2
014/05/28/androidnotification-messageat-a-particular-timerepeated-every-timethe-app-launched/) on
Tutorial #41: Using
AlarmManager and
BroadcastReceiver in
Android
(http://karanbalkar.co
m/2013/07/tutorial41-usingalarmmanager-andbroadcastreceiver-inandroid/#comment1611)

Tags

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

android,
birthday,

So now lets
widget!

begin

implementing

the Bubble

Button,

c++, college,
engineering,

event,

friendship, games,

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'
my_btn=Button(text='Press to view bubble'
layout.add_widget(my_btn)
root.add_widget(layout)
return root
def show_bubble(self,*args):

glass,

goldengate,

google, google maps,


image,

java,

Java EE, jQuery, json,

jython,

kivy, life,

memories, milestone,
MySQL, network,
notification,

ODI,

openCV, open source,

oracle,

PhoneGap, processing,

python, qt 5, sony,
Struts 2, tool,

website, widget,

windows, xml,

def show_bubble(self,*args):
my_bubble= Bubble(orientation = 'horizontal'
#Customizing my bubble
Categories
my_bubble.background_color =(20, 0, 0, .
my_bubble.border = [50, 50, 50, 10]
my_bubble.arrow_pos= 'top_left'
Personal
my_bub_btn1= BubbleButton(text='Copy',size_hint
my_bub_btn2= BubbleButton(text='Cut',size_hint (http://karanbalkar.co
my_bub_btn3= BubbleButton(text='Paste',size_hintm/category/personal/)
#Add items to bubble
Poems
my_bubble.add_widget(my_bub_btn1)
my_bubble.add_widget(my_bub_btn2)
(http://karanbalkar.co
my_bubble.add_widget(my_bub_btn3)
m/category/poems/)
self.add_widget(my_bubble)
if __name__ == '__main__':
MyBubbleApp().run()

Tech
(http://karanbalkar.co
m/category/tech/)

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

Tips And Tricks


(http://karanbalkar.co
m/category/tips-andtricks/)

Archives
July 2014
(http://karanbalkar.co
m/2014/07/)
June 2014
(http://karanbalkar.co
m/2014/06/)
May 2014
(http://karanbalkar.co
m/2014/05/)

(http://karanbalkar.com/2013/05/learning-kivybubble/bubble_demo_1/)

March 2014
(http://karanbalkar.co
m/2014/03/)
February 2014
(http://karanbalkar.co
m/2014/02/)
January 2014
(http://karanbalkar.co
m/2014/01/)
December 2013
(http://karanbalkar.co
m/2013/12/)
November 2013
(http://karanbalkar.co
m/2013/11/)
October 2013
(http://karanbalkar.co
m/2013/10/)

m/2013/10/)
September 2013
(http://karanbalkar.co
m/2013/09/)
August 2013
(http://karanbalkar.co
m/2013/08/)

(http://karanbalkar.com/2013/05/learning-kivybubble/bubble_demo_2/)
Posted in Tech (http://karanbalkar.com/category/tech/) |
Tagged Bubble (http://karanbalkar.com/tag/bubble/), kivy
(http://karanbalkar.com/tag/kivy/), python

July 2013
(http://karanbalkar.co
m/2013/07/)
June 2013
(http://karanbalkar.co
m/2013/06/)

(http://karanbalkar.com/tag/python/), widget
(http://karanbalkar.com/tag/widget/) | Leave a comment
(http://karanbalkar.com/2013/05/learning-kivybubble/#respond) |

May 2013
(http://karanbalkar.co
m/2013/05/)
April 2013
(http://karanbalkar.co
m/2013/04/)

Learning Kivy:
TabbedPanel
(http://karanbalkar.com/2
013/05/learning-kivytabbedpanel/)
Posted on MA Y 1 9 , 2 0 1 3
(HT T P:/ / KA R A NBA LKA R .COM/ 2 0 1 3 / 0 5 / LE A R NINGKIVY-T A BBE DPA NE L/ ) by KA R A N BA LKA R
(HT T P:/ / KA R A NBA LKA R .COM/ A UT HOR / KA R A NBA LK
AR/)

Hello everyone!
On May 13th, 2013 Kivy launched version 1.7.0 for
its platform. The new version includes some cool
features as well. You can have a look at the
changelog
from
over
here
(http://kivy.org/#changelog).
Todays Kivy tutorial talks about one of the existing
complex UX widgets called TabbedPanel. The
TabbedPanel
(http://kivy.org/docs/apikivy.uix.tabbedpanel.html)

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.

March 2013
(http://karanbalkar.co
m/2013/03/)
February 2013
(http://karanbalkar.co
m/2013/02/)
January 2013
(http://karanbalkar.co
m/2013/01/)
November 2012
(http://karanbalkar.co
m/2012/11/)
October 2012
(http://karanbalkar.co
m/2012/10/)
September 2012
(http://karanbalkar.co
m/2012/09/)

understand the concept of a TabbedPanelHeader.


What is a TabbedPanelHeader?
An individual tab is called a TabbedPanelHeader
(http://kivy.org/docs/apikivy.uix.tabbedpanel.html#kivy.uix.tabbedpanel.Tab
bedPanelHeader). 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
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'
#Create button tab
th_btn_head = TabbedPanelHeader(text=
th_btn_head.content= Button(text='This is my button'
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!

should get the following output!

(http://karanbalkar.com/2013/05/learning-kivytabbedpanel/kivy_tabbedpanel_2/)

(http://karanbalkar.com/2013/05/learning-kivytabbedpanel/kivy_tabbedpanel_3/)

(http://karanbalkar.com/2013/05/learningkivy-tabbedpanel/kivy_tabbedpanel_1/)
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, thats it for this tutorial. Keep visiting for some
more interesting Kivy tutorials!
Posted in Tech (http://karanbalkar.com/category/tech/) |
Tagged kivy (http://karanbalkar.com/tag/kivy/), python
(http://karanbalkar.com/tag/python/), tabbedpanel
(http://karanbalkar.com/tag/tabbedpanel/) | 3 Comments
(http://karanbalkar.com/2013/05/learning-kivytabbedpanel/#comments) |

Learning Kivy: Accordion


(http://karanbalkar.com/2
013/05/learning-kivyaccordion/)
Posted on MA Y 5 , 2 0 1 3
(HT T P:/ / KA R A NBA LKA R .COM/ 2 0 1 3 / 0 5 / LE A R NINGKIVY-A CCOR DION/ ) by KA R A N BA LKA R
(HT T P:/ / KA R A NBA LKA R .COM/ A UT HOR / KA R A NBA LK
AR/)

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
Accordion
is
basically
a
Widget
(http://kivy.org/docs/api-kivy.uix.widget.html)
in
the form of a menu where in the options are

stacked either horizontally or vertically. An


Accordion will contain one or many AccordionItem
(http://kivy.org/docs/api-kivy.uix.accordion.html?
highlight=accordion#kivy.uix.accordion.AccordionIt
em) instances such that each item when touched
opens up displaying its underlying content.
The
current
implementation
AccordionItem into two parts:

divides

the

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
kivy.uix.accordion.html?

(http://kivy.org/docs/api-

highlight=accordion#kivy.uix.accordion.AccordionIt
em.title).
[AccordionItemTitle@Label]:
text: ctx.title
canvas.before:
Color:
rgb: 1, 1, 1
BorderImage:
source:
ctx.item.background_normal \
if ctx.item.collapse \
else ctx.item.background_selected
pos: self.pos
size: self.size
PushMatrix
Translate:
xy: self.center_x, self.center_y
Rotate:
angle: 90 if ctx.item.orientation =
axis: 0, 0, 1
Translate:
xy: -self.center_x, -self.center_y
canvas.after:
PopMatrix

Now, lets 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!


Accordion.py
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'
src = "images/%d.jpg" % x
image = Image(source=src,pos=(400,
# add image to AccordionItem
item.add_widget(image)
root.add_widget(item)
return root
if __name__ == '__main__':
SampleAccorApp().run()
Run the above code by writing kivy Accordion.py
inside command prompt.

(http://karanbalkar.com/2013/05/learning-kivyaccordion/kivy_accordion_1/)

(http://karanbalkar.com/2013/05/learningkivy-accordion/kivy_accordion_2/)
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'
background_selected='image_when_selected.png')
So, thats it for this tutorial. Hope it helps you in
some way! Thanks
Posted in Tech (http://karanbalkar.com/category/tech/) |
Tagged Accordion (http://karanbalkar.com/tag/accordion/),
kivy (http://karanbalkar.com/tag/kivy/), widget
(http://karanbalkar.com/tag/widget/) | 6 Comments
(http://karanbalkar.com/2013/05/learning-kivyaccordion/#comments) |

Learning Kivy: Canvas


(http://karanbalkar.com/2
013/04/learning-kivycanvas/)
Posted on A PR IL 1 4 , 2 0 1 3
(HT T P:/ / KA R A NBA LKA R .COM/ 2 0 1 3 / 0 4 / LE A R NINGKIVY-CA NVA S / ) by KA R A N BA LKA R
(HT T P:/ / KA R A NBA LKA R .COM/ A UT HOR / KA R A NBA LK
AR/)

Hey everyone!
In
my
previous
(http://karanbalkar.com/2013/04/learning-kivycarousel-and-asyncimage/) 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

From the Kivy documentation, the Graphics


(http://kivy.org/docs/api-kivy.graphics.html)
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

(http://kivy.org/docs/api-

kivy.graphics.instructions.html) is a root object


used for drawing by a Widget. The Canvas supports
Pythons with statement and its 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 Pythons with statement
with self.canvas:
Color(1., 1., 0)
Rectangle(size=(50, 50))
Now, heres 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.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
#function to clear rectangle from screen
def reset_rects(self,wid,*largs):
wid.canvas.clear()
def build(self):
wid = Widget()
#calling function with default arguments
btn_add = Button(text='Draw rectangle',on_press
btn_clear = Button(text='Clear',on_press
layout = GridLayout(cols=1,rows=2)
layout.add_widget(btn_add)
layout.add_widget(btn_clear)
root=GridLayout()
root.add_widget(wid)
root.add_widget(layout)
return root
if __name__ == '__main__':
CanvasApp().run()
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!

(http://karanbalkar.com/2013/04/learningkivy-canvas/kivy_canvas_demo/)
Output

Posted in Tech (http://karanbalkar.com/category/tech/) |


Tagged canvas (http://karanbalkar.com/tag/canvas/),
graphics (http://karanbalkar.com/tag/graphics/), kivy
(http://karanbalkar.com/tag/kivy/) | 3 Comments
(http://karanbalkar.com/2013/04/learning-kivycanvas/#comments) |

Learning Kivy: Carousel


and AsyncImage
(http://karanbalkar.com/2
013/04/learning-kivycarousel-and-asyncimage/)
Posted on A PR IL 1 3 , 2 0 1 3
(HT T P:/ / KA R A NBA LKA R .COM/ 2 0 1 3 / 0 4 / LE A R NINGKIVY-CA R OUS E L-A ND-A S YNCIMA GE / ) by KA R A N
BA LKA R
(HT T P:/ / KA R A NBA LKA R .COM/ A UT HOR / KA R A NBA LK
AR/)

Hello everyone!
Today I will talk about two interesting Widgets
(http://kivy.org/docs/guide/widgets.html) 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
(http://kivy.org/docs/api-kivy.uix.carousel.html)
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
(http://kivy.org/docs/apikivy.uix.carousel.html#kivy.uix.carousel.Carousel.lo
op). One can also navigate to the next slide or the
previous slide using the
(http://kivy.org/docs/api-

Carousel

properties

kivy.uix.carousel.html#kivy.uix.carousel.Carousel.pr
evious_slide).

Heres 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
for i in range(1,5):
#load pictures from images folder
src = "images/%d.jpg" % i
image = Image(source=src,pos=(400,
carousel.add_widget(image)
return carousel
if __name__ == '__main__':
Example1().run()

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!

(http://karanbalkar.com/2013/04/learningkivy-carousel-andasyncimage/kivy_carousel_view/)

asyncimage/kivy_carousel_view/)
Kivy Carousel View

Here
is
the
Source
code
(https://github.com/karanbalkar/KivyCarouselDemo
)
2. AsyncImage
Now, the AsyncImage
kivy.uix.image.html?

(http://kivy.org/docs/api-

highlight=async%20image#kivy.uix.image.AsyncIm
age) 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.
Heres 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
asynchronously!

some

images

getting

loaded

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
for i in range(1,5):
src = "http://placehold.it/480x270.png&text=slide-%d&.png
#load images asynchronously
image = Factory.AsyncImage(source=src, allow_stretch
carousel.add_widget(image)
return carousel
if __name__ == '__main__':
Example1().run()
So thats it for this tutorial. I will talk about the
Graphics
(http://kivy.org/docs/apikivy.graphics.html) module of the Kivy framework
in my further tutorials! Enjoy!
Posted in Tech (http://karanbalkar.com/category/tech/) |
Tagged async image (http://karanbalkar.com/tag/asyncimage/), carousel (http://karanbalkar.com/tag/carousel/),
kivy (http://karanbalkar.com/tag/kivy/) | 4 Comments
(http://karanbalkar.com/2013/04/learning-kivy-carousel-

(http://karanbalkar.com/2013/04/learning-kivy-carouseland-asyncimage/#comments) |

Learning Kivy: Animate


widgets
(http://karanbalkar.com/2
012/10/learning-kivyanimate-widgets/)
Posted on OCT OBE R 2 9 , 2 0 1 2
(HT T P:/ / KA R A NBA LKA R .COM/ 2 0 1 2 / 1 0 / LE A R NINGKIVY-A NIMA T E -WIDGE T S / ) by KA R A N BA LKA R
(HT T P:/ / KA R A NBA LKA R .COM/ A UT HOR / KA R A NBA LK
AR/)

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
(http://kivy.org/docs/apikivy.animation.html) 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
anim.start(widget)
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.)
anim.start(widget)

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
(http://kivy.org/docs/apikivy.animation.html#kivy.animation.AnimationTran
sition) 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'
anim.start(widget)
Here is a sample program to demonstrate the
Animation module in Kivy:
import kivy
kivy.require('1.4.0')
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
button.bind(on_press=self.on_button_press)
parent.add_widget(button)
return parent
def on_button_press(self,instance):
anim = Animation(x=50, size=(50, 50
#apply sequential animation
anim += Animation(pos=(200,70),t='in_out_back'
#apply parallel animation
anim &= Animation(size=(100,50))
anim.start(instance)
if __name__== '__main__':
MyAnimApp().run()

You can write the above code using the Python


IDLE and run it as:
kivy yourfilename.py
Posted in Tech (http://karanbalkar.com/category/tech/) |
Tagged animation (http://karanbalkar.com/tag/animation/),
kivy (http://karanbalkar.com/tag/kivy/) | 4 Comments
(http://karanbalkar.com/2012/10/learning-kivy-animatewidgets/#comments) |

Learning Kivy: Video Player


and Scatter widgets
(http://karanbalkar.com/2
012/10/learning-kivyvideo-player-and-scatterwidgets/)
Posted on OCT OBE R 1 5 , 2 0 1 2
(HT T P:/ / KA R A NBA LKA R .COM/ 2 0 1 2 / 1 0 / LE A R NINGKIVY-VIDE O-PLA YE R -A ND-S CA T T E R -WIDGE T S / ) by
KA R A N BA LKA R
(HT T P:/ / KA R A NBA LKA R .COM/ A UT HOR / KA R A NBA LK
AR/)

Hello everyone!

Today I would like to share with you something new


that I learnt recently while working on the Kivy
(http://kivy.org/docs/index.html) 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
(http://kivy.org/docs/apikivy.uix.widget.html) 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 (http://kivy.org/docs/apikivy.uix.screenmanager.html)
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
(http://kivy.org/docs/api-kivy.uix.videoplayer.html)
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
(http://kivy.org/docs/apikivy.uix.videoplayer.html#kivy.uix.videoplayer.Vide
oPlayerAnnotation).
Step 2: You can open any editor like Notepad++ to
write the code. I will be using the Python IDLE for
now.
import kivy
kivy.require('1.4.0')
from kivy.app import App

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
button.bind(on_press=on_button_press)
parent.add_widget(button) #add button
return parent
def on_button_press(self):
video= VideoPlayer(source='softboy.avi'
parent.add_widget(video) #add videoplayer
return parent
if __name__ == '__main__':
MyApp().run()

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 its size.

(http://karanbalkar.com/?
attachment_id=439#main)
VideoPlayer widget snapshot 1

(http://karanbalkar.com/?
attachment_id=440#main)
VideoPlayer widget snapshot 2

Scatter widget
The
Scatter
(http://kivy.org/docs/apikivy.uix.scatter.html) 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
kivy.require('1.4.0')
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__':
MyApp().run()
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.

(http://karanbalkar.com/?
attachment_id=442#main)
Drag image

(http://karanbalkar.com/?
attachment_id=443#main)
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!
Posted in Tech (http://karanbalkar.com/category/tech/) |
Tagged kivy (http://karanbalkar.com/tag/kivy/), Scatter
(http://karanbalkar.com/tag/scatter/), Video Player
(http://karanbalkar.com/tag/video-player/), widget
(http://karanbalkar.com/tag/widget/) | 1 Comment
(http://karanbalkar.com/2012/10/learning-kivy-videoplayer-and-scatter-widgets/#comments) |

Tutorial #6: Working with


Camera in Kivy
(http://karanbalkar.com/2
012/10/tutorial-6-workingwith-camera-in-kivy/)
Posted on OCT OBE R 1 , 2 0 1 2
(HT T P:/ / KA R A NBA LKA R .COM/ 2 0 1 2 / 1 0 / T UT OR IA L6 -WOR KING-WIT H-CA ME R A -IN-KIVY/ ) by KA R A N
BA LKA R
(HT T P:/ / KA R A NBA LKA R .COM/ A UT HOR / KA R A NBA LK
AR/)

Hey everyone, here is a new post that demonstrates


the use of the Camera (http://kivy.org/docs/apikivy.core.camera.html) module in Kivy.
For those who are new to Kivy, I suggest you read
the
Getting
started
tutorial
for
Kivy
(http://karanbalkar.com/2012/09/getting-started-

with-kivy/) before proceeding.


This tutorial describes the use of Camera, how to
open a camera and take a screenshot of the live
stream.
So lets 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
cam.play=True
#Start the camera
camwidget.add_widget(cam)
button=Button(text='screenshot'
button.bind(on_press=self.doscreenshot)
camwidget.add_widget(button)
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 (http://kivy.org/docs/api-

kivy.uix.camera.html), Window
(http://kivy.org/docs/api-kivy.core.window.html)
and Button (http://kivy.org/docs/apikivy.uix.button.html)
Posted in Tech (http://karanbalkar.com/category/tech/) |
Tagged camera (http://karanbalkar.com/tag/camera/), kivy
(http://karanbalkar.com/tag/kivy/), python
(http://karanbalkar.com/tag/python/) | 3 Comments
(http://karanbalkar.com/2012/10/tutorial-6-working-withcamera-in-kivy/#comments) |

Getting started with Kivy


(http://karanbalkar.com/2
012/09/getting-startedwith-kivy/)
Posted on S E PT E MBE R 2 5 , 2 0 1 2
(HT T P:/ / KA R A NBA LKA R .COM/ 2 0 1 2 / 0 9 / GE T T INGS T A R T E D-WIT H-KIVY/ ) by KA R A N BA LKA R
(HT T P:/ / KA R A NBA LKA R .COM/ A UT HOR / KA R A NBA LK
AR/)

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.
Lets start by downloading Kivy for Windows from
here
:
Kivy
for
Windows
(http://kivy.org/#download).
Unzip the downloaded file to find the kivy.bat file
shown below:

(http://karanbalkar.com/2012/09/getting-startedwith-kivy/kivy1/)
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, lets 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'
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:

(http://karanbalkar.com/2012/09/getting-startedwith-kivy/kivy2/)
Posted in Tech (http://karanbalkar.com/category/tech/) |
Tagged cross platform (http://karanbalkar.com/tag/crossplatform/), kivy (http://karanbalkar.com/tag/kivy/), python
(http://karanbalkar.com/tag/python/) | 2 Comments
(http://karanbalkar.com/2012/09/getting-started-withkivy/#comments) |

TH R EA D S O F L IF E

You might also like