UI 2-1#
Ipywidgets and Interact in Jupyter
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.
1# Necessary imports to make this work
2from IPython.display import display
3from ipywidgets import interact_manual
1# Example:
2vals = [ 'red', 'white', 'blue'] # this is a list type, it will generate a dropdown widget
3min, max, step = 0, 20, 0.5 # this is the range of the slider, and the steps
4text = "testing" # this is a string type, it will generate a textbox
5
6@interact_manual(color=vals, grade=(min,max,step), name=text) # DECORATOR function with values
7def on_click(color, grade, name): # DECORATED function. This code
8 display(color) # runs when the button is clicked
9 display(grade) # (thus the name on_click)
10 display(name)
Note#
For more complex interactions we will use the streamlit library
Challenge 2-2-1#
Let’s create a simple widget interaction for display student status for their GPA:
inputs:
student name
major: one of “IMT”, “IST”, or “ADA”
gpa between 0.0 and 4.0
process:
when gpa < 1.8 then status is “probation”
when gpa > 3.4 then status is “deans list”
else status is “no list”
output:
display the following statement: “NAME in MAJOR with GPA is on STATUS”