To use IPython widgets in the notebook, the widget namespace needs to be imported.
from IPython.html import widgets # Widget definitions from IPython.display import display # Used to display widgets in the notebook
IPython comes with basic widgets that represent common interactive controls. These widgets are
A few special widgets are also included, that can be used to capture events and change how other widgets are displayed. These widgets are
To see the complete list of widgets, one can execute the following
[widget for widget in dir(widgets) if widget.endswith('Widget')]
['AccordionWidget', 'BoundedFloatTextWidget', 'BoundedIntTextWidget', 'ButtonWidget', 'CheckboxWidget', 'ContainerWidget', 'DOMWidget', 'DropdownWidget', 'FloatProgressWidget', 'FloatSliderWidget', 'FloatTextWidget', 'HTMLWidget', 'ImageWidget', 'IntProgressWidget', 'IntSliderWidget', 'IntTextWidget', 'LatexWidget', 'PopupWidget', 'RadioButtonsWidget', 'SelectWidget', 'TabWidget', 'TextWidget', 'TextareaWidget', 'ToggleButtonWidget', 'ToggleButtonsWidget', 'Widget']
The basic widgets all have sensible default values. Create a FloatSliderWidget without displaying it:
mywidget = widgets.FloatSliderWidget()
Constructing a widget does not display it on the page. To display a widget, the widget must be passed to the IPython
display(object) method or must be returned as the last item in the cell.
mywidget is displayed by
It's important to realize that widgets are not the same as output, even though they are displayed with
display. Widgets are drawn in a special widget area. That area is marked with a close button which allows you to collapse the widgets. Widgets cannot be interleaved with output. Doing so would break the ability to make simple animations using
Widgets are manipulated via special instance attributes (traitlets). The names of these traitlets are listed in the widget's
keys attribute (as seen below). A few of these attributes are common to most widgets. The basic attributes are
_view_name are private attributes that exist in all widgets and should not be modified.
['_view_name', 'orientation', 'min', 'max', '_css', 'value', 'disabled', 'visible', 'step', 'description']
Changing a widget's attribute will automatically update that widget everywhere it is displayed in the notebook. Here, the
value attribute of
mywidget is set. The slider shown above updates automatically with the new value. Syncing also works in the other direction - changing the value of the displayed widget will update the property's value.
mywidget.value = 25.0
After changing the widget's value in the notebook by hand to 0.0 (sliding the bar to the far left).
Widget values can also be set with kwargs during the construction of the widget (as seen below).
mysecondwidget = widgets.RadioButtonsWidget(values=["Item A", "Item B", "Item C"], value="Item A") display(mysecondwidget)