Skip to main content
Jupyter Notebooks
CHAPTER 13 Beginner

Interactive Widgets in Jupyter

Updated: May 18, 2026
5 min read

# CHAPTER 13

Interactive Widgets in Jupyter

1. Chapter Introduction

Up until now, our notebooks have been static. You run the code, and a fixed chart or number appears. But what if you want a stakeholder to adjust a variable—like the interest rate on a loan—and see a chart update instantly *without* them having to touch any Python code? This is possible using ipywidgets. This chapter teaches you how to turn your static notebook into an interactive dashboard.

2. Installing ipywidgets

To use widgets, you need the library installed. Run this in a cell if you don't have it: !pip install ipywidgets

Cell 1:

python
1234567891011121314
import ipywidgets as widgets
from IPython.display import display

# Let's verify it works by creating a simple slider
slider = widgets.IntSlider(
    value=50,
    min=0,
    max=100,
    step=1,
    description='Volume:'
)

# Display the slider in the notebook
display(slider)

*(When you run this, a clickable, draggable slider appears in your notebook!)*

3. Reading Values from a Widget

A widget is useless unless you can use the value the user selected. You access the current state of a widget using .value.

Cell 2:

python
12
# Run this cell AFTER you drag the slider from Cell 1
print(f"The user selected a volume of: {slider.value}")

*Note: This is manual. You have to drag the slider, then run Cell 2. Next, we will learn how to make it update automatically.*

4. The @interact Decorator (The Magic Trick)

The easiest way to link a widget to Python code automatically is the @interact decorator. You place it directly above a function. When the user moves the widget, it instantly re-runs the function with the new value.

Cell 3:

python
12345678
from ipywidgets import interact

# Place the decorator above the function
# By passing x=10, interact automatically generates an IntSlider
@interact(x=10)
def multiply_by_five(x):
    result = x * 5
    print(f"{x} multiplied by 5 is {result}")

*(Drag the slider generated by this cell. Notice the text updates instantly!)*

5. Other Types of Widgets

interact is smart. It looks at the default value you provide and guesses the correct widget type.

Cell 4:

python
1234567891011121314151617
# 1. Boolean (True/False) -> Creates a Checkbox
@interact(show_details=False)
def toggle_view(show_details):
    if show_details:
        print("Detailed View: Access Granted.")
    else:
        print("Basic View.")

# 2. String -> Creates a Text Box
@interact(name="Guest")
def greet(name):
    print(f"Welcome to the dashboard, {name}!")

# 3. List of Strings -> Creates a Dropdown Menu
@interact(department=['Sales', 'HR', 'IT'])
def select_dept(department):
    print(f"Loading data for the {department} department...")

6. Mini Project: Interactive Financial Dashboard

Let's combine widgets with Matplotlib to create an interactive chart where the user controls the data. We will simulate compound interest.

Cell 5:

python
1234567891011121314151617181920
import matplotlib.pyplot as plt
import numpy as np

# Create the interactive function
@interact(principal=(1000, 10000, 500), rate=(1.0, 10.0, 0.5), years=(1, 30, 1))
def plot_compound_interest(principal, rate, years):
    
    # Calculate interest over time
    time = np.arange(1, years + 1)
    # Compound interest formula: A = P(1 + r/100)^t
    amount = principal * (1 + rate/100) ** time
    
    # Plot the results
    plt.figure(figsize=(8, 4))
    plt.plot(time, amount, color='green', marker='o')
    plt.title(f"Growth of ${principal} at {rate}% over {years} years")
    plt.xlabel("Years")
    plt.ylabel("Total Value ($)")
    plt.grid(True)
    plt.show()

*(When executed, this creates three sliders. As you move them, the Matplotlib chart redraws itself in real-time!)*

7. Common Mistakes

  • Forgetting plt.show() inside the interact function: If you generate a Matplotlib chart inside an interactive function but forget plt.show(), the chart might not update properly when the slider moves, or it might print ugly object text to the screen.
  • Slow functions: If the function takes 5 seconds to run (e.g., downloading a massive file), linking it to a slider is a bad idea. Every millimeter you drag the slider will trigger the 5-second function, freezing the notebook. Use a Button widget instead for slow tasks.

8. MCQs

Question 1

Which library is required to create interactive sliders and buttons in Jupyter?

Question 2

How do you display a manually created widget (like slider = widgets.IntSlider()) on the screen?

Question 3

How do you retrieve the current number selected on a slider widget stored in a variable named myslider?

Question 4

What is the easiest way to automatically link a widget to a function so it updates in real-time?

Question 5

If you use @interact(x=False), what type of widget will automatically be generated?

Question 6

If you use @interact(color=['Red', 'Green', 'Blue']), what type of widget is generated?

Question 7

Can you link an @interact widget to a Matplotlib chart?

Question 8

What happens if you link a highly complex, 10-second machine learning function to a fast-moving slider?

Question 9

If you want to prevent a slow function from running until the user is absolutely ready, what widget is better than a slider?

Question 10

The @interact command must be placed where relative to the function?

9. Interview Questions

  • Q: A non-technical manager wants to use your Jupyter Notebook to test different marketing budget scenarios. How would you design the notebook so they don't have to edit any Python code?
  • Q: Explain how the @interact decorator infers which widget to display based on the default arguments you provide.

10. Summary

Interactive widgets elevate Jupyter Notebooks from static documents to dynamic, app-like dashboards. The ipywidgets library provides sliders, dropdowns, checkboxes, and text boxes. The most powerful tool is the @interact decorator, which automatically generates the correct widget based on your default parameters and re-runs your function in real-time as the user plays with the UI.

11. Next Chapter Recommendation

In Chapter 14: Machine Learning Workflows in Jupyter, we will use Jupyter to orchestrate the entire machine learning lifecycle—from loading data and training a model with Scikit-Learn to evaluating its accuracy.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·