The ipywidgets package provides many common user interface controls for exploring code and data interactively. These controls can be assembled and customized to create complex graphical user interfaces. In this recipe, we introduce the various ways we can create user interfaces with ipywidgets.
Getting ready
The ipywidgets package should be installed by default in Anaconda, but you can also install it manually with conda install ipywidgets.
Alternatively, you can install ipywidgets with pip install ipywidgets, but then you also need to type the following command in order to enable the extension in the Jupyter Notebook:
>>> import ipywidgets as widgets
from ipywidgets import HBox, VBox
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
%matplotlib inline
The @interact decorator shows a widget for controlling the arguments of a function. Here, the function f() accepts an integer as an argument. By default, the @interact decorator displays a slider to control the value passed to the function:
>>> @widgets.interact
def f(x=5):
print(x)
The function f() is called whenever the slider value changes.
We can customize the slider parameters. Here, we specify a minimum and maximum integer range for the slider:
There is also an @interact_manual decorator that provides a button to call the function manually. This is useful with long-lasting computations that should not run every time a widget value changes. Here, we create a simple user interface for controlling four parameters of a function that displays a plot. There are two floating-point sliders, a drop-down menu for choosing a value among a few predefined options, and a checkbox for Boolean values:
In addition to the @interact and @interact_manual decorators, ipywidgets provides a simple API to create individual widgets. Here, we create a floating-point slider:
Now, we will see how to combine these widgets into a complex Graphical User Interface, and how to react to user interactions with these controls. We create a function that will display a plot as defined by the created controls. We can access the control value with the value property of the widgets:
The on_click decorator of a button widget lets us react to click events. Here, we simply declare that the plotting function should be called when the button is pressed:
To display all of our widgets in a unified graphical interface, we define a layout with two tabs. The first tab shows widgets related to the plot itself, whereas the second tab shows widgets related to the styling of the plot. Each tab contains a vertical stack of widgets defined with the VBox class:
The documentation for ipywidgets demonstrates many other features of the package. Styling the widgets can be customized. New widgets can be created by writing Python and JavaScript code (see the Creating custom Jupyter Notebook widgets in Python, HTML, and JavaScript recipe). Widgets can also remain at least partly functional in a static notebook export.