Creating custom Jupyter Notebook widgets in Python, HTML, and JavaScript
The ipywidgets packages provides many built-in control widgets to interact with code and data in the Jupyter Notebook. In this recipe, we show how to build a custom interactive widget from scratch, using Python on the kernel side, and HTML/JavaScript on the client side (frontend). The widget just displays two buttons to increase and decrease a number. The number can be accessed and updated either from the kernel (Python code) or the client (browser).
How to do it...
- Let's import the packages:
>>> import ipywidgets as widgets from traitlets import Unicode, Int, validate
- We create a
CounterWidget
class deriving fromDOMWidget
:>>> class CounterWidget(widgets.DOMWidget): _view_name = Unicode('CounterView').tag(sync=True) _view_module = Unicode('counter').tag(sync=True) value = Int(0).tag(sync=True)
This class represents the Python part of the widget. The...