Mastering Generative AI with OpenAI
Building an Interactive Chatbot
Using Widgets in Jupyter Notebook
Enhance your Jupyter Notebook with interactive widgets and layouts using Panel. Panel makes it easy to build dynamic interfaces directly in your notebook, turning static analyses into interactive explorations.
Table of Contents
- Prerequisites
- Step 1: Install and Enable Panel
- Step 2: Import Panel and Define Widgets
- Step 3: Create an Event Handler
- Step 4: Display Widgets in a Layout
- Widget Reference Table
- Additional Resources
Prerequisites
- Jupyter Notebook (or JupyterLab)
- Python 3.7+
- Panel library
Note
If you haven’t installed Panel yet, run:
pip install panel
Step 1: Install and Enable Panel
Start your notebook and enable Panel’s extension:
import panel as pn
# Activate Panel in this notebook
pn.extension()
Step 2: Import Panel and Define Widgets
Create a text input and a button. The text input will display the click count.
# TextInput widget initialized with a default message
text_input = pn.widgets.TextInput(value='Ready')
# Button widget with a primary style
button = pn.widgets.Button(name='Click me', button_type='primary')
Step 3: Create an Event Handler
Define a callback function to update the text input whenever the button is clicked:
def increment_clicks(event):
"""Update the text_input value based on button.clicks."""
text_input.value = f'Clicked {button.clicks} times'
# Register the handler
button.on_click(increment_clicks)
Step 4: Display Widgets in a Layout
Arrange the button and text input side by side using pn.Row
:
# Render the widgets in a single row
pn.Row(button, text_input)
After running the cell above, you’ll see:
- A Click me button
- A text box initially showing Ready
Each click updates the text box to reflect the total number of clicks, demonstrating a simple interactive interface.
Widget Reference Table
Widget | Purpose | Key Property |
---|---|---|
TextInput | Display and update dynamic text | value='Ready' |
Button | Capture and respond to user clicks | button_type='primary' |
Additional Resources
- Panel Documentation: https://panel.holoviz.org/
- JupyterLab: https://jupyterlab.readthedocs.io/
Build on this pattern to create dashboards, data explorers, and more within your Jupyter environment!
Watch Video
Watch video content