Playground

Widgets


In [2]:
import ipywidgets as widgets
widgets.Widget.widget_types.values()


Out[2]:
[ipywidgets.widgets.widget_string.Text,
 ipywidgets.widgets.widget_string.Latex,
 ipywidgets.widgets.widget_box.Box,
 ipywidgets.widgets.widget_controller.Axis,
 ipywidgets.widgets.widget_bool.Checkbox,
 ipywidgets.widgets.widget_int.IntRangeSlider,
 ipywidgets.widgets.widget_selection.RadioButtons,
 ipywidgets.widgets.widget_string.HTML,
 ipywidgets.widgets.widget_float.FloatRangeSlider,
 ipywidgets.widgets.widget_box.PlaceProxy,
 ipywidgets.widgets.widget_selection.ToggleButtons,
 ipywidgets.widgets.widget_int.IntText,
 ipywidgets.widgets.widget_selection.Dropdown,
 ipywidgets.widgets.widget_bool.Valid,
 ipywidgets.widgets.widget_bool.ToggleButton,
 ipywidgets.widgets.widget_float.FloatSlider,
 ipywidgets.widgets.widget_int.IntProgress,
 ipywidgets.widgets.widget_selection.SelectMultiple,
 ipywidgets.widgets.widget_float.FloatProgress,
 ipywidgets.widgets.widget_color.ColorPicker,
 ipywidgets.widgets.widget_box.FlexBox,
 ipywidgets.widgets.widget_string.Textarea,
 ipywidgets.widgets.widget_float.BoundedFloatText,
 ipywidgets.widgets.widget_controller.Button,
 ipywidgets.widgets.widget_selection.Select,
 ipywidgets.widgets.widget_selectioncontainer.Accordion,
 ipywidgets.widgets.widget_float.FloatText,
 ipywidgets.widgets.widget_image.Image,
 ipywidgets.widgets.widget_button.Button,
 ipywidgets.widgets.widget_int.BoundedIntText,
 ipywidgets.widgets.widget_box.Proxy,
 ipywidgets.widgets.widget_selectioncontainer.Tab,
 ipywidgets.widgets.widget_int.IntSlider,
 ipywidgets.widgets.widget_controller.Controller]

In [3]:
from ipywidgets import widgets
from IPython.display import display

float_slider = widgets.FloatSlider(
    value=7.5,
    min=5.0,
    max=10.0,
    step=0.1,
    description='Float Slider Horizontal:',
)
display(float_slider)

float_slider_vert = widgets.FloatSlider(
    value=7.5,
    min=5.0,
    max=10.0,
    step=0.1,
    description='Float Slider Vertical',
    orientation='vertical',
)
display(float_slider_vert)

float_progress = widgets.FloatProgress(
    value=7.5,
    min=5.0,
    max=10.0,
    step=0.1,
    description='Float Progress:',
)
display(float_progress)

bounded_float_text = widgets.BoundedFloatText(
    value=7.5,
    min=5.0,
    max=10.0,
    description='Bounded Float Text:',
)
display(bounded_float_text)

float_text = widgets.FloatText(
    value=7.5,
    description='Float Text:',
)
display(float_text)

toggle_button = widgets.ToggleButton(
    description='Toggle Button',
    value=False,
)
display(toggle_button)

checkbox = widgets.Checkbox(
    description='Checkbox',
    value=True,
)
display(checkbox)

# Read Only Widget
valid = widgets.Valid(
    value=True,
)
display(valid)

# Selection Widget
from IPython.display import display
dropdown1 = widgets.Dropdown(
    options=['1', '2', '3'],
    value='2',
    description='Dropbox 1:',
)
display(dropdown1)
dropdown1.value

dropdown2 = widgets.Dropdown(
    options={'One': 1, 'Two': 2, 'Three': 3},
    value=2,
    description='Dropbox 2:',
)
display(dropdown2)
dropdown2.value

radio_buttons = widgets.RadioButtons(
    description='Radio Buttons:',
    options=['pepperoni', 'pineapple', 'anchovies'],
)
display(radio_buttons)

select = widgets.Select(
    description='Select:',
    options=['Linux', 'Windows', 'OSX'],
)
display(select)

#selection_slider = widgets.SelectionSlider(
#    description='Selection Slider',
#    options=['scrambled', 'sunny side up', 'poached', 'over easy'],
#)
#display(selection_slider)

toggle_buttons = widgets.ToggleButtons(
    description='Toggle Buttons:',
    options=['Slow', 'Regular', 'Fast'],
)
display(toggle_buttons)

select_multiple = widgets.SelectMultiple(
    description="Select Multiple",
    options=['Apples', 'Oranges', 'Pears']
)
display(select_multiple)

# String
string = widgets.Text(
    description='String:',
    value='Hello World',
)
display(string)

text_area = widgets.Textarea(
    description='String:',
    value='Hello World',
)
display(text_area)

#label = widgets.Label(
#    value="$$\\frac{n!}{k!(n-k)!} = \\binom{n}{k}$$",
#)
#display(label)

button = widgets.Button(description='Button')

Widget Events


In [4]:
text = widgets.Text()
display(text)

def handle_submit(sender):
    print(text.value)

text.on_submit(handle_submit)

In [5]:
from IPython.display import display
button = widgets.Button(description="Click Me!")
display(button)

def on_button_clicked(b):
    print("Button clicked.")

button.on_click(on_button_clicked)

File Upload Widget

Styling Widgets

Accordion


In [6]:
name1 = widgets.Text(description='Location:')
zip1 = widgets.BoundedIntText(description='Zip:', min=0, max=99999)
page1 = widgets.Box(children=[name1, zip1])

name2 = widgets.Text(description='Location:')
zip2 = widgets.BoundedIntText(description='Zip:', min=0, max=99999)
page2 = widgets.Box(children=[name2, zip2])

accord = widgets.Accordion(children=[page1, page2], width=400)
display(accord)

accord.set_title(0, 'From')
accord.set_title(1, 'To')

Tab widget


In [7]:
name = widgets.Text(description='Name:', padding=4)
name.padding = 4
color = widgets.Dropdown(description='Color:', options=['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'])
color.padding = 4
page1 = widgets.Box(children=[name, color])
page1.padding = 4

age = widgets.IntSlider(description='Age:', min=0, max=120, value=50)
age.padding = 4
gender = widgets.RadioButtons(description='Gender:', options=['male', 'female'])
gender.padding = 4
page2 = widgets.Box(children=[age, gender])
page2.padding = 4

tabs = widgets.Tab(children=[page1, page2])
display(tabs)

tabs.set_title(0, 'Name')
tabs.set_title(1, 'Details')

Alignment


In [8]:
# Vertical
buttons = [widgets.Button(description=str(i)) for i in range(3)]
display(*buttons)

# Horizontal
container = widgets.HBox(children=buttons)
display(container)

interact

Creates UI Elements automatically


In [9]:
def h(p, q):
  return (p, q)
widgets.interact?
widgets.interact(h, p=5, q=fixed(20))

widgets.interact(f, var=widgets.IntSlider(min=-10, max=30, step=1, value=10))

widgets.interact(f, var=10)
widgets.interact(f, var=(-10,10)) # min, max
widgets.interact(f, var=(-100,1000,100)) # min, max ,step

widgets.interact(f, var=False)
widgets.interact(f, var=True)
widgets.interact(f, var="Textbox")
widgets.interact(f, var=("orange","apple"))
widgets.interact(f, var={"one":1,"two":2})


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-8be4eeacbcd8> in <module>()
      2   return (p, q)
      3 get_ipython().magic(u'pinfo widgets.interact')
----> 4 widgets.interact(h, p=5, q=fixed(20))
      5 
      6 widgets.interact(f, var=widgets.IntSlider(min=-10, max=30, step=1, value=10))

NameError: name 'fixed' is not defined

interactive


In [ ]:
def f(a, b):
    return a+b

w = interactive(f, a=10, b=20)
print("Widget Type=> {}".format(type(w)))
print("Widget Childreen=> {}".format(w.children))
display(w) # display widget
print("Widget Argument=> {}".format(w.kwargs))
print("Widget Result=> {}".format(w.result))

In [ ]:
from traitlets import link
a = FloatText()
b = FloatSlider()
display(a,b)

mylink = link((a, 'value'), (b, 'value'))
# unlink
mylink.unlink()

Examples


In [ ]:
from IPython.html.widgets import *
import numpy as np
import math
t = np.arange(0.0, 1.0, 0.01)

def pltsin(f):
  plt.plot(x, math.sin(2*math.pi*t*f))
  plt.show()

widgets.interact(pltsin, f=(1,10,0.1))

In [ ]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

from ipywidgets import interactive
from IPython.display import Audio, display
import numpy as np

def beat_freq(f1=220.0, f2=224.0):
    max_time = 3
    rate = 8000
    times = np.linspace(0,max_time,rate*max_time)
    signal = np.sin(2*np.pi*f1*times) + np.sin(2*np.pi*f2*times)
    print(f1, f2, abs(f1-f2))
    display(Audio(data=signal, rate=rate))
    return signal
  
v = interactive(beat_freq, f1=(200.0,300.0), f2=(200.0,300.0))
display(v)
v.kwargs

f1, f2 = v.children
f1.value = 255
f2.value = 260
plt.plot(v.result[0:6000])

In [ ]:
from ipywidgets import interact

%matplotlib inline
import matplotlib.pyplot as plt

import networkx as nx

# wrap a few graph generation functions so they have the same signature

def random_lobster(n, m, k, p):
    return nx.random_lobster(n, p, p / m)

def powerlaw_cluster(n, m, k, p):
    return nx.powerlaw_cluster_graph(n, m, p)

def erdos_renyi(n, m, k, p):
    return nx.erdos_renyi_graph(n, p)

def newman_watts_strogatz(n, m, k, p):
    return nx.newman_watts_strogatz_graph(n, k, p)

def plot_random_graph(n, m, k, p, generator):
    g = generator(n, m, k, p)
    nx.draw(g)
    plt.show()

interact(plot_random_graph, n=(2,30), m=(1,10), k=(1,10), p=(0.0, 1.0, 0.001),
        generator={'lobster': random_lobster,
                   'power law': powerlaw_cluster,
                   'Newman-Watts-Strogatz': newman_watts_strogatz,
                   u'Erdős-Rényi': erdos_renyi,
                   });