# Necessary imports to make this work
from IPython.display import display
from ipywidgets import interact_manual1. Interaction in Jupyter using ipywidgets
To do this tutorial you will need ipywidgets installed in your conda environment. To do that:
Open a terminal (from in VS Code, click “Terminal” -> “New Terminal”).
Activate your
ist356conda environment by running:conda activate ist356Install
ipywidgetsby either running:pip install ipywidgetsor:
conda install -c conda-forge -y ipywidgets
Notebook widgets: ipywidgets
The jupyter notebook widgets create better UI interactions in notebooks. This is called the ipywidgets library. There is a lot to this library but we will keep our interactions simple.
To replace input() statements we use the interact_manual decorator function. Like a hat decorates your head, decorator function adds code to another function.
interact_manual decorator does the following:
- generates a textbox for any string input
- generates a slider for any int/float input
- generates a dropdown for any list input
- generates a button titled “Run interact”
When the button is clicked the code inside the decorated function is executed and the widget values are used as input. Use display() instead of print() for output.
# Example:
vals = [ 'red', 'white', 'blue'] # this is a list type, it will generate a dropdown widget
min, max, step = 0, 20, 0.5 # this is the range of the slider, and the steps
text = "testing" # this is a string type, it will generate a textbox
@interact_manual(color=vals, grade=(min,max,step), name=text) # DECORATOR function with values
def on_click(color, grade, name): # DECORATED function. This code
display(color) # runs when the button is clicked
display(grade) # (thus the name on_click)
display(name)For more complex interactions we will use the streamlit library