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. 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.

2. 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.

READ :   How To Use IPython Jupyter Notebook To Develop Python Code

add slide bar to python function in jupyter notebook

Leave a Reply

Your email address will not be published. Required fields are marked *

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