Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Widgets and Visualization

Interactive Widgets with ipywidgets

Build interactive controls in Jupyter with ipywidgets: interact and sliders, widget values, observe callbacks, buttons, layout boxes, output areas and how widget state syncs with the kernel.

A static notebook shows one answer. A notebook with widgets lets the reader move a slider, pick an option, press a button, and watch the result change immediately. That turns an analysis into a small interactive tool: a function you can explore, a parameter you can tune, a model whose behaviour you can feel. The standard library for this is ipywidgets.

ipywidgets needs a live kernel and browser front end, which this site does not have. The ipywidgets code is read-only. The stand-ins implement the ideas, an observable value, callbacks, and automatic control generation, in plain Python, so you can run and understand them.

Install and first widget

Terminal
python -m pip install ipywidgets

In current JupyterLab and Notebook 7 no extra step is needed. In a cell:

Python
import ipywidgets as widgets

slider = widgets.IntSlider(value=5, min=0, max=10, description="Count:")
slider

The slider appears in the output. Move it and read its current value in the next cell:

Python
slider.value        # an int, always the slider's present position

Every widget has a value (or a similar property such as index or checked) and options such as description, disabled, layout. Common widgets:

Widget Value type Use
IntSlider, FloatSlider, FloatRangeSlider number(s) Numeric parameter
IntText, FloatText number Typed number
Dropdown, RadioButtons, SelectMultiple choice(s) Pick from a list
Checkbox, ToggleButton bool On/off flag
Text, Textarea, Password str Free text
DatePicker, ColorPicker date, color Specialised inputs
Button clicks (event) Run an action
Output nothing A region to print or plot into
HBox, VBox, Tab, Accordion children Layout

interact: the one-line version

interact takes a function and automatically creates a control for each argument, calls the function whenever a control changes, and shows its output:

Python
from ipywidgets import interact

def power(base, exponent):
    return base ** exponent

interact(power, base=(1, 10), exponent=(0, 5));

The abbreviations decide the control type: a tuple (min, max) of ints gives an integer slider, a tuple of floats a float slider, a list of strings a dropdown, a bool a checkbox, a string a text box. interact is also available as a decorator:

Python
@interact(color=["red", "green", "blue"], size=(10, 50, 5))
def show(color, size):
    print(f"{size}px {color}")

Tip: when the function does expensive work, use interact_manual, which adds a Run button and calls the function only when you press it.

Stand-in: how interact picks controls

The next stand-in does what interact does at its heart: inspects abbreviations and creates a control description for each, then calls the function with a set of values:

Python Stand-in: build controls from abbreviations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reacting to changes: observe

For more control than interact, connect to a widget's changes yourself. observe registers a callback that runs whenever a trait (property) changes:

Python
slider = widgets.IntSlider(value=1, min=0, max=10)
label = widgets.Label()

def on_change(change):
    label.value = f"squared: {change['new'] ** 2}"

slider.observe(on_change, names="value")
widgets.VBox([slider, label])

The change dictionary has name, old, new, owner and type. This is the observer pattern: the widget notifies whoever subscribed. Here is a stand-in with exactly this protocol, which you can run:

Python Stand-in: an observable widget

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that setting the same value triggers nothing: widgets only notify on a real change.

Buttons and the Output widget

A Button emits clicks rather than values; use on_click. An Output widget is a place to show text or plots that you control, separate from the cell's own output:

Python
button = widgets.Button(description="Roll")
out = widgets.Output()

def on_click(b):
    with out:
        out.clear_output()
        print("Rolled:", random.randint(1, 6))

button.on_click(on_click)
widgets.VBox([button, out])

Without an Output, prints made inside a callback may appear in the wrong place (or in the server log), because callbacks run outside the cell's execution.

Layout

Boxes arrange widgets: HBox horizontally, VBox vertically, GridBox as a grid, Tab and Accordion as panels. The layout argument controls width, margin and similar CSS-like properties:

Python
a = widgets.IntSlider(description="A", layout=widgets.Layout(width="300px"))
b = widgets.IntSlider(description="B", style={"description_width": "40px"})
widgets.HBox([a, b])

A good control panel groups related inputs, keeps labels short, and puts the result right beside the controls.

How it works: model in the kernel, view in the browser

A widget is two objects: a model in the kernel (the Python object you hold) and one or more views in the browser. They share state through the kernel's messaging channel, using comm messages (see Kernels explained). When you drag a slider, the browser view updates the model's value in the kernel, your callbacks run, and any changed widget sends its new value back to the browser.

sequenceDiagram
    participant U as User
    participant V as View in browser
    participant M as Model in kernel
    U->>V: drags slider to 7
    V->>M: comm message: value = 7
    M->>M: run observe callbacks
    M->>V: comm message: label.value updated
    V->>U: label shows "squared: 49"

The view only displays; all logic lives in Python in the kernel.

Consequences: widgets work only while a kernel is alive. A notebook shared as a static HTML file shows widgets that do not respond, unless you save their state (File โ†’ Save Widget State) and embed it, which gives a snapshot rather than live behaviour. For a notebook that others use interactively, host it with a live kernel (see the deployment chapter), or turn it into an app (also covered later).

Linking widgets

Sometimes two widgets should stay in sync without Python callbacks. jslink connects them in the browser (fast and works even in some static exports); link does it through the kernel:

Python
a = widgets.IntSlider()
b = widgets.IntText()
widgets.jslink((a, "value"), (b, "value"))
widgets.HBox([a, b])

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does interact(f, x=(0, 10)) create?

    A tuple of ints becomes an IntSlider, and interact calls f each time the control changes.
  2. 2. How do you run code whenever a widget's value changes?

    observe registers a callback that receives a change dictionary with old and new values.
  3. 3. Why do widgets in an exported static HTML file usually not respond?

    The model and callbacks live in the Python kernel; a static file has no kernel to run them.
  4. 4. What is the Output widget for?

    Use with out: to direct prints and plots from a callback to that area.

Summary

  • ipywidgets provides sliders, dropdowns, checkboxes, text boxes, buttons and layout containers.
  • interact builds controls from function arguments and re-runs the function on change; interact_manual adds a Run button.
  • observe reacts to trait changes; Button.on_click handles clicks; Output captures callback output.
  • Widgets are a model in the kernel and a view in the browser, synchronised by comm messages.
  • Static exports show widgets without live behaviour; interactive use needs a kernel.
  • jslink links widgets in the browser, link through the kernel.

Next: Tables and DataFrame display