Examples#
IPython includes an interactive widget architecture that combines Python code running in the kernel and JavaScript/HTML/CSS running in the browser. These widgets allow users to interactively examine their code and data.
Interact function#
ipywidgets.interact automatically creates user interface (UI) controls to interactively explore code and data.
[1]:
from __future__ import print_function
import ipywidgets as widgets
from ipywidgets import fixed, interact, interact_manual, interactive
In the simplest case, interact automatically generates controls for function arguments and then calls the function with those arguments when you interactively edit the controls. The following is a function that returns its only argument x.
[2]:
def f(x):
return x
Slider#
If you specify a function with an integer keyword argument (x=10), a slider is generated and bound to the function parameter:
[3]:
interact(f, x=10);
Checkbox#
If you specify True or False, interact generates a checkbox:
[4]:
interact(f, x=True);
Text area#
If you pass a string, interact generates a text area:
[5]:
interact(f, x="Hi Pythonistas!");
Decorator#
interact can also be used as a decorator. This way you can define a function and interact with it in a single setting. As the following example shows, interact also works with functions that have multiple arguments:
[6]:
@interact(x=True, y=1.0)
def g(x, y):
return (x, y)