How To Add Interactive Widget ( Slide Bar ) In Jupyter Notebook

In previous article, we have tell you how to add rich media output component ( audio, video, image etc) in jupyter notebook. But all those widgets are not interactive. This article will show you an example about how to add a slide bar in jupyter notebook. When you slide the bar, it will change the python function input parameter value to the slide bar value accordingly, and then the python function result will be displayed in the jupyter notebook web page.

1. Install ipywidgets In Python Library.

  1. Check whether ipywidgets has been installed in your python environment. If you see below output, that means ipywidgets has been installed.
    (python_example) C:\Users\zhaosong>pip show ipywidgets
    Name: ipywidgets
    Version: 7.5.1
    Summary: IPython HTML widgets for Jupyter
    Author: IPython Development Team
    Author-email: [email protected]
    License: BSD
    Location: c:\users\zhaosong\anaconda3\envs\python_example\lib\site-packages
    Requires: ipython, nbformat, widgetsnbextension, ipykernel, traitlets
  2. If ipywidgets has not been installed, run below code to install it.
    > pip install ipywidgets

2. Use Interact Decorator To Add Slide Bar To Python Function.

To add a slide bar to a special python function in jupyter notebook, you just need to import ipywidget.interact decorator, then use it to decorate the python function, then the slide bar current value will be passed to the python function by the x argument.

You can add one slide bar to one python function defined in the jupyter notebook by decorate each function with @interactdecorator. If your ipython version is before 4.0, then you should use IPython.html.widgets.interact to defin the interactive slide bar.

3. Add Slide Bar To Python Function By @interact Decorator Example.

This example defines two python function, and add @interact decorator to each of the function. Input below python source code in jupyter notebook line cell.

# import ipywidgets.interact class, this class will represent a slide bar.
from ipywidgets import interact

# use interact decorator to decorate the function, so the function can receive the slide bar's value with parameter x.
@interact(x=(0, 100))
def double_number(x):
    print("The double of %d is %d." % (x, x*2))
# add another slide bar to this function with the interact decorator.    
@interact(y=(0, 10))
def square_number(y):
    print("The square of %d is %d." % (y, y**2))

When you run above source code, there will display two slide bar under above code, and you can slide each bar to see the python function output in the web page.

add slide bar to python function in jupyter notebook

0 0 vote
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x