One of the main new features in IPython 2.0 is interactive widgets.

Some additional references:


In [1]:
# need to be running at least version 2 of IPython

import IPython
IPython.version_info


Out[1]:
(3, 0, 0, 'dev')

In [2]:
from IPython.display import display, Image, HTML, clear_output

In [3]:
from IPython.html import widgets

In [4]:
# what's in widgets

dir(widgets)


Out[4]:
['AccordionWidget',
 'BoundedFloatTextWidget',
 'BoundedIntTextWidget',
 'ButtonWidget',
 'CallbackDispatcher',
 'CheckboxWidget',
 'ContainerWidget',
 'DOMWidget',
 'DropdownWidget',
 'FloatProgressWidget',
 'FloatSliderWidget',
 'FloatTextWidget',
 'HTMLWidget',
 'ImageWidget',
 'IntProgressWidget',
 'IntSliderWidget',
 'IntTextWidget',
 'LatexWidget',
 'PopupWidget',
 'RadioButtonsWidget',
 'SelectWidget',
 'TabWidget',
 'TextWidget',
 'TextareaWidget',
 'ToggleButtonWidget',
 'ToggleButtonsWidget',
 'Widget',
 '__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 '__path__',
 'fixed',
 'interact',
 'interaction',
 'interactive',
 'widget',
 'widget_bool',
 'widget_button',
 'widget_container',
 'widget_float',
 'widget_image',
 'widget_int',
 'widget_selection',
 'widget_selectioncontainer',
 'widget_string']

In [7]:
import math

def fac(x):
    print math.factorial(x)
    
fac(10)


3628800

In [6]:
# let's dispaly factorial of input x
widgets.interact(fac,x=(0,1000,1))


1

In [8]:
# how to set starting value of a widget?

widgets.interact(fac,
                 x=widgets.IntSliderWidget(min=0,max=1000,step=1,value=10))


3628800
Out[8]:
<function __main__.fac>

In [9]:
from jinja2 import Template
import uuid

def square(r,g,b,a):

    html_template = """
    <style>

    #{{div_id}} {
        background-color: rgba({{r}},{{g}},{{b}},{{a}});
        height:100px;
        width:100px;
    }

    </style>

    <div id="{{div_id}}"/>"""
    
    div_id="i" + str(uuid.uuid4())

    html_src = Template(html_template).render(r=r, g=g, b=b, a=a, div_id=div_id)
    display(HTML(html_src))
        
square(255,0,255,1)



In [10]:
widgets.interact(square,
                 r=widgets.IntSliderWidget(min=0,max=255,step=1,value=0),
                 g=widgets.IntSliderWidget(min=0,max=255,step=1,value=0),
                 b=widgets.IntSliderWidget(min=0,max=255,step=1,value=0),
                 a=widgets.FloatSliderWidget(min=0,max=1,value=1)
                )



In [11]:
#hsla
# https://en.wikipedia.org/wiki/HSL_and_HSV

import colorsys

def square_hsla(h,s,l,a):

    html_template = """
    <style>

    #{{div_id}} {
        background-color:hsla({{h}},{{s}}%,{{l}}%,{{a}});
        height:100px;
        width:100px;
    }

    </style>

    <div id="{{div_id}}"/>"""
    
    div_id="i" + str(uuid.uuid4())

    html_src = Template(html_template).render(h=h, s=s, l=l, a=a, div_id=div_id)
    
    (r,g,b) = colorsys.hls_to_rgb(float(h)/360.0,float(l)/100.0,float(s)/100.0)
    print (int(r*255+0.5), int(g*255+0.5), int(b*255+0.5))
    
    display(HTML(html_src))
    
square_hsla(120,100,50,0.3)


(0, 255, 0)

In [ ]:
widgets.interact(square_hsla,
                 h=widgets.FloatSliderWidget(min=0,max=360,value=120),
                 s=widgets.FloatSliderWidget(min=0,max=100,value=100),
                 l=widgets.FloatSliderWidget(min=0,max=100,value=50),
                 a=widgets.FloatSliderWidget(min=0,max=1,value=0.3)
                )

SVG example


In [12]:
%%html
<svg height="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>



In [13]:
def circle(r=40):
    
    cx = int(1.25*r)
    cy = cx
    height = 2*cx
    
    html = """<svg height="{height}">
  <circle cx="{cx}" cy="{cy}" r="{r}" stroke="black" stroke-width="3" fill="red" />
</svg>
""".format(height=height, cx=cx, cy=cy, r=r)
    display(HTML(html))

In [16]:
circle(r=200)



In [17]:
widgets.interact(circle, r=(0,500,5))


Animating a float slider widget


In [18]:
w = widgets.FloatSliderWidget()
w.min = 0
w.max  = 200
w.value = 30

In [19]:
w

In [22]:
w.value = 10

In [23]:
import time

for m in range(0,200,2):
    w.value = m
    time.sleep(0.1)

In [ ]:
w.keys

In [ ]:
w.close()

In [24]:
m = widgets.interact(circle, r=(0,500,5))
m


Out[24]:
<function __main__.circle>

Expanding and shrinking circle


In [25]:
for r in range (0,500,5):
    m.widget._children[0].value = r
    time.sleep(0.1)
    
for r in range (500,0,-5):
    m.widget._children[0].value = r
    time.sleep(0.1)


Text widget and Pig Latin


In [26]:
#http://stackoverflow.com/a/20304752/7782

def pigLatin(aString):
    index = 0
    stringLength = len(aString)
    consonants = ''

    # if aString starts with a vowel then just add 'way' to the end
    if isVowel(aString[index]): 
        return aString + 'way' 
    else:
    # the first letter is added to the list of consonants
        consonants += aString[index]
        index += 1

        # if the next character of aString is a vowel, then from the index 
        # of the vowel onwards + any consonants + 'ay' is returned
        while index < stringLength:
            if isVowel(aString[index]):
                return aString[index:stringLength] + consonants + 'ay'
            else:
                consonants += aString[index]
                index += 1
        return 'This word does contain any vowels.'

def isVowel(character):
    vowels = 'aeiou'
    return character in vowels

def echoPL(s):
    print pigLatin(s)

widgets.interact(echoPL, s="hello")


owcay

In [ ]: