Basics

import ipywidgets as widgets
from IPython.display import display
 
# Basic Usage
w = widgets.IntSlider(value=10)
display(w)
w.close()
 
# Link two widgets
w_t = widgets.FloatText(value=10)
w_s = widgets.FloatSlider()
display(w_t, w_s)
link = widgets.jslink((w_t, 'value'), (w_s, 'value'))
# Unlink
link.unlink()

Widget List

Numeric

widgets.IntSlider()
widgets.FloatSlider(orientation='horizontal')
widgets.FloatLogSlider() # min and max is the exponent of base.
widgets.IntRangeSlider()
widgets.FloatRangeSlider()
widgets.IntProgress()
widgets.FloatProgress()
widgets.BoundedIntText()
widgets.BoundedFloatText()
widgets.FloatText()
widgets.IntText()

Boolean

widgets.ToggleButton()
widgets.Checkbox(indent=False) # indent is an option for align
widgets.Valid() # read-only

Selection

widgets.Dropdown(options=[1, 2, 3])
widgets.Dropdown(options=[('one', 1), ('two', 2), ('three', 3)], value=2)
widgets.RadioButtons(options=[1, 2, 3])
widgets.Select(options=[1, 2, 3])
widgets.SelectionSlider(options=[1, 2, 3])
widgets.SelectionRangeSlider(options=[1, 2, 3])
widgets.ToggleButtons(options=[1, 2, 3])
widgets.SelectMultiple(options=[1, 2, 3])

String

widgets.Text(placeholder='Type something')
widgets.Textarea()
widgets.Combobox(options=['aaa', 'bbb', 'ccc'], ensure_option=True)
widgets.Password()
widgets.Label(value=r"$\frac{1}{2}$")
widgets.HTML(value="Hello <b>World</b>")
widgets.HTMLMath(value=r"Some math and <i>HTML</i>: \(x^2\) and $$\frac{x+1}{x-1}$$")

Image

widgets.Image(value=image,format='png',width=300,height=400) # where the input image is byte-stream

Button

widgets.Button(description="Click me")

play

play = widgets.Play(value=10, min=0, max=100, interval=10)
slider = widgets.IntSlider()
widgets.jslink((play, 'value'), (slider, 'value'))
widgets.HBox([play, slider])

Tag

widgets.TagsInput(value=['aaa', 'bbb'], allowed_tags=['aaa', 'bbb', 'ccc', 'ddd'], allow_duplicates=False)
widgets.ColorsInput(value=['red', '#2f6d30'])
widgets.FloatsInput()
widgets.IntsInput(format='$,d')

Date/Time

widgets.DatePicker()
widgets.TimePicker()
widgets.DatetimePicker()

Color

widgets.ColorPicker()

File

uploader = widgets.FileUpload()
display(uploader) # -> list(dict(name=str, type=str, size=int, content=memory, last_modified=datetime))
# upload file[s]
with open('test_file.txt', 'wb') as fp:
    fp.write(uploader.value[0][content'])

Layout

Boxes

items = [widgets.Label(str(i)) for i in range(4)]
widgets.Box(items)
widgets.HBox(items)
widgets.VBox(items)

GridBox

widgets.GridBox(items, layout=widgets.Layout(grid_template_columns="repeat(3, 100px)"))

Arccodian

widgets.Accordion(items)
widgets.Tab(items, titles=[f'Tab {e}' for e in range(len(items))])

Stack

dropdown = widgets.Dropdown(options=['button', 'slider'])
stack = widgets.Stack([widgets.Button(description='Click'), widgets.IntSlider()], selected_index=0)
widgets.jslink((dropdown, 'index'), (stack, 'selected_index'))
widgets.VBox([dropdown, stack])

Output Widget

Output

out = widgets.Output(layout={'border': '1px solid black'})
with out:
    for i in range(3):
        print(i, 'Hello world!')
display(out)

Interactive Output

a = widgets.IntSlider(description='a')
b = widgets.IntSlider(description='b')
c = widgets.IntSlider(description='c')
def f(a, b, c):
    print('{}*{}*{}={}'.format(a, b, c, a*b*c))
 
out = widgets.interactive_output(f, {'a': a, 'b': b, 'c': c})
 
widgets.HBox([widgets.VBox([a, b, c]), out])

Widget Events

Special event

button = widgets.Button(description="Click Me!")
output = widgets.Output()
 
display(button, output)
 
def on_button_clicked(b):
    with output:
        print("Button clicked.")
 
button.on_click(on_button_clicked)

Traitlet event

int_range = widgets.IntSlider()
output = widgets.Output()
 
display(int_range, output)
 
def on_value_change(change):
    output.clear_output()
    with output:
        print(change['new'])
 
int_range.observe(on_value_change, names='value')

Linking

Bidirectional linking

caption = widgets.Label(value='The values of slider1 and slider2 are synchronized')
sliders1, slider2 = widgets.IntSlider(description='Slider 1'), widgets.IntSlider(description='Slider 2')
l = widgets.link((sliders1, 'value'), (slider2, 'value'))
display(caption, sliders1, slider2)

One directional linking

caption = widgets.Label(value='Changes in source values are reflected in target1')
source, target1 = widgets.IntSlider(description='Source'), widgets.IntSlider(description='Target 1')
dl = widgets.dlink((source, 'value'), (target1, 'value'))
display(caption, source, target1)

Linking with callback

caption = widgets.Label(value='The slider value is in its initial position.')
slider = widgets.IntSlider(min=-5, max=5, value=1, description='Slider')
 
def handle_slider_change(change):
    caption.value = 'The slider value is ' + (
        'negative' if change.new < 0 else 'nonnegative'
    )
 
slider.observe(handle_slider_change, names='value')
display(caption, slider)

Client-side linking

caption = widgets.Label(value='The values of range1 and range2 are synchronized')
range1, range2 = widgets.IntSlider(description='Range 1'),\
                 widgets.IntSlider(description='Range 2')
jsl = widgets.jslink((range1, 'value'), (range2, 'value'))
display(caption, range1, range2)
 
caption = widgets.Label(value='Changes in source_range values are reflected in target_range1')
source_range, target_range1 = widgets.IntSlider(description='Source range'),\
                              widgets.IntSlider(description='Target range 1')
jsdl = widgets.jsdlink((source_range, 'value'), (target_range1, 'value'))
display(caption, source_range, target_range1)

Continuous update

c = widgets.IntSlider(description="Continuous", continuous_update=True) # widgets are updated while drag 
d = widgets.IntText(description="Continuous", continuous_update=True) # widgets are updated while typing

Interact

Interact automatically creates UI controls

Interact

The return value of the function will be displayed automatically

import ipywidgets as widgets
from IPython.display import display
from ipywidgets import interact, interactive, interact_manual
 
def f(x):
    return x
interact(f, x=10) 
 
@interact(x=True, y=widgets.IntSlider(5, 1, 15))
def g(x, y):
    return (x, y)

Interactive

The return value of the function will not be displayed automatically

def f(a, b):
    display(a + b)
    return a+b
 
w = interactive(f, a=10, b=20)
display(w)

Manual update

Update the button is clicked.

@interact_manual(x=True, y=widgets.IntSlider(5, 1, 15))
def g(x, y):
    return (x, y)

Prevent Flickering of Plot

import matplotlib.pyplot as plt
import numpy as np
 
def f(m, b):
    plt.figure(2)
    x = np.linspace(-10, 10, num=1000)
    plt.plot(x, m * x + b)
    plt.ylim(-5, 5)
    plt.show()
 
interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
output = interactive_plot.children[-1]
output.layout.height = '500px'
interactive_plot