IPyWidgets
ipywidgets adds interactive GUI controls - sliders, buttons, text boxes, dropdowns - to notebooks. Widgets communicate with the kernel over the same messaging channel, so a UI update triggers Python code and Python code can update the UI. It is the fastest way to turn a notebook into a little experiment station.
Install
pip install ipywidgets
jupyter nbextension enable --py widgetsnbextension # classic notebook
# JupyterLab ships widget support via the @jupyter-widgets/jupyterlab-manager extension
Basic Widgets
from ipywidgets import interact
def f(x, y=5, step=2):
return x + y
interact(f, x=5, y=5, step=2) # renders sliders for x and y
interact creates a slider for each numeric parameter and runs the function on every change - a one-line interactive demo.
Manual Widget Code
import ipywidgets as widgets
def on_change(change):
print("slider now at", change["new"])
slider = widgets.IntSlider(value=50, min=0, max=100, description="Value")
slider.observe(on_change, names="value")
out = widgets.Output()
with out:
print("current:", slider.value)
widgets.VBox([slider, out]).layout.height = "120px"
# display the VBox; last line of a cell
Common Widget Types
- IntSlider, FloatSlider, IntRangeSlider - numeric controls.
- Checkbox, RadioButtons, Select, Dropdown - discrete choices.
- Text, Textarea, HTML, Label - text display and input.
- Button, Output, VBox, HBox, Tab - structure and action.
Patterns That Work
- Demo a parameter sweep: sliders bound to model hyperparameters, an Output box showing the result.
- Drive a function that is expensive: debounce by reacting on release (observe on the "value" change only when the slider is released).
- Build small tools: a form (VBox of Text widgets + Button) that writes a report.
Summary
ipywidgets turns notebook cells into interactive UIs: use interact for one-line demos with sliders, or build VBox/HBox layouts of IntSlider, Button, Text, and Output widgets with .observe callbacks. It is the standard way to add controls to exploratory notebooks and to build lightweight data tools.