Jupyter Interactive Widgets (ipywidgets)
ipywidgets is a Python library that provides interactive HTML widgets for Jupyter notebooks and the IPython kernel. It enables users to create interactive controls like sliders, text boxes, and buttons, bringing notebooks to life and allowing interactive exploration of data and models. The current version is 8.1.8, and it maintains an active development cycle with regular patch and minor releases, and major versions typically every few years.
Warnings
- breaking The `FileUpload` widget API changed significantly in version 8.x. The `.data` and `.metadata` traits were removed, and the `.value` trait was revamped to be a list of dictionaries, each containing file information (e.g., `content`, `name`, `type`, `size`, `last_modified`).
- breaking The `description_tooltip` attribute, used for tooltips on some widgets, was deprecated in favor of a universal `tooltip` attribute available on all widgets inheriting `DOMWidget` in version 8.x.
- breaking The `description` field of most widgets now sanitizes HTML content by default. If you rely on custom HTML in descriptions, it will be stripped or rendered as plain text.
- breaking The method for setting titles on container widgets like `Accordion` or `Tab` changed. Direct calls to `container.set_title(index, title)` can cause `IndexError` if not handled correctly. It is now recommended to initialize with a `titles` tuple or assign to the `_titles` trait.
- gotcha Direct `print()` statements within functions linked to widgets (especially with `@interact` or `widget.observe()`) may not always display reliably or may appear in the console instead of the notebook output area in newer Jupyter environments.
Install
-
pip install ipywidgets
Imports
- ipywidgets
import ipywidgets as widgets
- interact
from ipywidgets import interact
- display
from IPython.display import display
- Button
from ipywidgets import Button
- VBox
from ipywidgets import VBox
- Output
from ipywidgets import Output
Quickstart
import ipywidgets as widgets
from IPython.display import display, HTML, clear_output
# Create a simple IntSlider widget
slider = widgets.IntSlider(
min=0,
max=100,
step=1,
description='Value:',
value=50
)
# Create an Output widget to capture print statements
output = widgets.Output()
# Define a function to be called when the slider's value changes
def on_value_change(change):
with output:
clear_output()
print(f"Slider value changed to: {change['new']}")
# Observe changes in the slider's value
slider.observe(on_value_change, names='value')
# Display the slider and the output area
display(HTML("<h3>Interactive Slider Example</h3>"))
display(slider, output)