Playground

Widgets


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

In [9]:
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 [10]:
text = widgets.Text()
display(text)

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

text.on_submit(handle_submit)



In [11]:
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 [12]:
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 [6]:
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 [7]:
# 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(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-5f590769bad0> in <module>()
      2   return (p, q)
      3 
----> 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 [9]:
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))


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-d42fd24b42ca> in <module>()
      2     return a+b
      3 
----> 4 w = interactive(f, a=10, b=20)
      5 print("Widget Type=> {}".format(type(w)))
      6 print("Widget Childreen=> {}".format(w.children))

NameError: name 'interactive' is not defined

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

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


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-99fbb3f0d824> in <module>()
      1 from traitlets import link
----> 2 a = FloatText()
      3 b = FloatSlider()
      4 display(a,b)
      5 

NameError: name 'FloatText' is not defined

Examples


In [11]:
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))


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-a751e60fdb7b> in pltsin(f)
      5 
      6 def pltsin(f):
----> 7   plt.plot(x, math.sin(2*math.pi*t*f))
      8   plt.show()
      9 

NameError: name 'plt' is not defined
Out[11]:
<function __main__.pltsin>

In [1]:
%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])


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-ad99241fa8fa> in <module>()
     20 v.kwargs
     21 
---> 22 f1, f2 = v.children
     23 f1.value = 255
     24 f2.value = 260

ValueError: too many values to unpack (expected 2)

In [13]:
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,
                   });