iInteractive Widgets in Google Colab using ipywidgets



Interactive Python GUIs in Colab | ipywidgets Tutorial for Beginners #colab #python

Google Colab supports interactive widgets through the ipywidgets library, enabling us to build dynamic user interfaces directly within our Python notebooks. These widgets simplify real-time input, output, and visualization—making it easier to prototype or demonstrate Python applications without needing a separate GUI framework.

This tutorial includes over 10 widget examples such as sliders, buttons, dropdowns, layout containers, and more.

šŸ“„ A complete sample notebook is available for download at the bottom of this page. Quick access links are also provided throughout this post to jump between widget examples and sections.

Using IntSlider, Button, and Label Widgets 🔝

from ipywidgets import VBox, HBox, IntSlider, Button, Label

# Create an integer slider widget with a description, minimum, maximum, and initial value.
slider = IntSlider(description='Value:', min=0, max=100, value=50)

# Create a button widget with a description and style.
button = Button(description='Click Me', button_style='warning')

# Create a label widget with an initial value.
label = Label(value='Adjust the slider and click the button.')

# Define a function to be executed when the button is clicked.
def on_click(b):
    # Update the label's value to show the current value of the slider.
    label.value = f'Slider is at {slider.value}'

# Attach the on_click function to the button's click event.
button.on_click(on_click)

# Arrange the widgets vertically in a VBox and display them.
VBox([slider, button, label])
Output
Widgets slider button and Label

šŸ“„ Jump to notebook download

from ipywidgets import Dropdown, Checkbox, Text, Output, VBox

# Create a dropdown widget with options
dropdown = Dropdown(
    options=['Python', 'JavaScript', 'PHP'],
    description='Language:'
)

# Create a checkbox to accept terms
checkbox = Checkbox(
    value=False,
    description='Accept terms'
)

# Create a text input widget
text_input = Text(
    placeholder='Type your name',
    description='Name:'
)

# Create an output area to show messages
output = Output()

# Define an interaction function
def display_info(change):
    output.clear_output()
    with output:
        if checkbox.value:
            print(f"Hello {text_input.value}, you selected {dropdown.value}.")
        else:
            print("You must accept the terms.")

# Attach the function to the widgets
dropdown.observe(display_info, names='value')
checkbox.observe(display_info, names='value')
text_input.observe(display_info, names='value')

# Display all widgets together
VBox([text_input, dropdown, checkbox, output])
Output
Widgets checkbox dropdown and text_input

šŸ“„ Jump to notebook download

Using IntRangeSlider, ToggleButtons, and ColorPicker Widgets 🔝

from ipywidgets import IntRangeSlider, ToggleButtons, ColorPicker, Button, Output, VBox

# Range slider for selecting a numeric range
range_slider = IntRangeSlider(
    value=[20, 80],
    min=0,
    max=100,
    step=5,
    description='Range:'
)

# Toggle buttons for selecting a mode
mode_selector = ToggleButtons(
    options=['Simple', 'Advanced', 'Expert'],
    description='Mode:'
)

# Color picker for selecting a color
color_picker = ColorPicker(
    value='#00aa00',
    description='Color:'
)

# A submit button
submit_btn = Button(
    description='Submit',
    button_style='success'
)

# Output area to show results
output = Output()

# Define what happens on button click
def show_results(b):
    output.clear_output()
    with output:
        print(f"Selected range: {range_slider.value}")
        print(f"Mode: {mode_selector.value}")
        print(f"Color: {color_picker.value}")

submit_btn.on_click(show_results)

# Show all widgets vertically
VBox([range_slider, mode_selector, color_picker, submit_btn, output])
Output
Widgets IntRangeSlider ToggleButtons and ColorPicker

šŸ“„ Jump to notebook download

Using DatePicker, Textarea, and FileUpload Widgets 🔝

from ipywidgets import DatePicker, Textarea, FileUpload, Button, Output, VBox

# Date picker for selecting a date
date_picker = DatePicker(
    description='Pick a date:'
)

# Text area for multi-line input
text_area = Textarea(
    placeholder='Enter your notes here...',
    description='Notes:',
    layout={'width': '400px', 'height': '100px'}
)

# File upload widget
file_upload = FileUpload(
    description='Upload File'
)

# Submit button
submit_btn = Button(
    description='Submit',
    button_style='info'
)

# Output widget to show results
output = Output()

# Define the event handler
def process_inputs(b):
    output.clear_output()
    with output:
        print(f"Date selected: {date_picker.value}")
        print(f"Notes:\n{text_area.value}")
        if file_upload.value:
            print(f"{len(file_upload.value)} file(s) uploaded.")
        else:
            print("No files uploaded.")

submit_btn.on_click(process_inputs)

# Display all widgets together
VBox([date_picker, text_area, file_upload, submit_btn, output])
Output
Widgets DatePicker Textarea and FileUpload

šŸ“„ Jump to notebook download

Using BoundedFloatText, Password, and RadioButtons Widgets 🔝

from ipywidgets import BoundedFloatText, Password, RadioButtons, Output, Button, VBox

# Bounded float text input
price_input = BoundedFloatText(
    value=10.0,
    min=1.0,
    max=100.0,
    step=0.5,
    description='Price:'
)

# Password input
password_input = Password(
    description='Password:',
    placeholder='Enter password'
)

# Radio buttons for payment mode
payment_mode = RadioButtons(
    options=['Credit Card', 'PayPal', 'Bank Transfer'],
    description='Payment:'
)

# Output and button
output = Output()
submit_btn = Button(
    description='Pay',
    button_style='danger'
)

# Define event logic
def process_payment(b):
    output.clear_output()
    with output:
        print(f"Amount: ${price_input.value}")
        print(f"Payment mode: {payment_mode.value}")
        print("Password received.")

submit_btn.on_click(process_payment)

# Display layout
VBox([price_input, password_input, payment_mode, submit_btn, output])
Output
Widgets BoundedFloatText Password and RadioButtons

šŸ“„ Jump to notebook download

Using Play, IntText, and FloatProgress with jslink 🔝

from ipywidgets import Play, IntText, FloatProgress, HBox, jslink

# Play widget to animate through values
play = Play(
    interval=200,
    value=0,
    min=0,
    max=100,
    description='Press play',
    disabled=False
)

# IntText to display the value of the play slider
int_text = IntText()
jslink((play, 'value'), (int_text, 'value'))

# Progress bar to reflect the current value
progress = FloatProgress(
    value=0,
    min=0,
    max=100,
    description='Progress:'
)
jslink((play, 'value'), (progress, 'value'))

# Display all horizontally
HBox([play, int_text, progress])
Output
Widgets Play IntText and FloatProgress

šŸ“„ Jump to notebook download

Widget Layout and Style Options 🔝

In addition to basic widget functionality, ipywidgets allows you to customize appearance using layout and style attributes. These options help in aligning, sizing, and styling widgets to create more polished interfaces in Google Colab or Jupyter notebooks.

from ipywidgets import Button, Layout, IntSlider

# A button with custom width and height
b1 = Button(
    description='Click Me',
    layout=Layout(width='200px', height='50px')
)

# A slider with full width and no description
s1 = IntSlider(
    layout=Layout(width='100%')
)

# Display widgets
display(b1, s1)

You can combine layout options like width, height, margin, and display to build responsive UI elements inside your notebooks.


šŸ“„ Jump to notebook download

Using Container Widgets: Accordion, Tab, and GridBox 🔝

Container widgets in ipywidgets—like Accordion, Tab, and GridBox—allow you to organize content efficiently. These are especially helpful when dealing with grouped widgets or when you want to switch between sections without cluttering the interface.

from ipywidgets import Accordion, Tab, GridBox, IntSlider, Checkbox, Layout

# Example 1: Accordion with two widgets
accordion = Accordion(children=[IntSlider(), Checkbox()])
accordion.set_title(0, 'Slider')
accordion.set_title(1, 'Checkbox')

# Example 2: Tab widget with same children
tab = Tab(children=[IntSlider(), Checkbox()])
tab.set_title(0, 'Tab 1')
tab.set_title(1, 'Tab 2')

# Example 3: GridBox for 2x2 widget layout
grid = GridBox(
    children=[
        IntSlider(), IntSlider(),
        Checkbox(), Checkbox()
    ],
    layout=Layout(grid_template_columns='50% 50%')
)

# Display widgets
display(accordion, tab, grid)

These container widgets help reduce visual clutter and organize interactive elements effectively. Accordion and Tab are ideal for toggling between sections, while GridBox provides a neat layout for multiple related widgets.


šŸ“„ Jump to notebook download

šŸ› ļø Try This Practice Project 🔝

Now that you’ve learned a variety of ipywidgets, here’s a fun mini‑project to reinforce your skills:

  • Objective: Build a simple interactive temperature converter with Celsius ↔ Fahrenheit conversion.
  • Widgets to use: FloatText or BoundedFloatText for input, RadioButtons to select conversion direction, a Button to trigger conversion, and an Output area to display results.
  • Bonus: Add a ColorPicker that changes the background color of the output box based on the result—cool blues for cold and warm reds for hot!

Feel free to extend the project further:

  • Add validation so that the button only works when a number is entered.
  • Use HBox or VBox to better layout the form.
  • Use GridBox for structured placement of widgets.

Share your solution or variations in the comments below—or link to your notebook so others can view your implementation!

Frequently Asked Questions 🔝

ipywidgets allows us to create interactive elements like sliders, buttons, and dropdowns within Google Colab notebooks for dynamic data input and UI controls.

No installation is required in Colab—it comes with ipywidgets pre-installed, so we can use it directly.

Yes, ipywidgets work seamlessly in Jupyter Notebooks, just like in Colab.

We can use layout containers like VBox and HBox to arrange multiple widgets vertically or horizontally.

Yes, we can use the jslink function to synchronize values between widgets like sliders, text boxes, or progress bars.

Summary of ipywidgets in Google Colab 🔝

This guide walked through the powerful interactive capabilities of ipywidgets in Google Colab. You explored a wide range of widgets including sliders, dropdowns, checkboxes, file uploads, progress bars, and more. We also covered layout and container options like HBox, VBox, Tab, and Accordion, giving you the tools to build dynamic, user-friendly interfaces in your notebooks.

WidgetPurpose
IntSlider, FloatProgressNumeric input & visual progress
Dropdown, RadioButtonsOption selection
Accordion, Tab, GridBoxOrganizing complex UI

Conclusion 🔝

ipywidgets makes it easy to turn your Python notebooks into interactive applications, especially in Google Colab where no extra setup is needed. Whether you're building a student-friendly demo, a data analysis tool, or a prototype UI, widgets offer a clean, responsive way to engage users. Continue exploring and combining widgets to match your project needs—and don't forget to link your widgets with logic and layout for the best user experience.

šŸ“„ Download Sample ipywidgets Notebook 🔝

Explore a ready-to-use Colab notebook demonstrating various ipywidgets in action. This includes interactive examples of sliders, buttons, dropdowns, layout controls, container widgets, and the mini temperature converter project. All source code featured in this blog post is included, allowing you to run, modify, and experiment directly within a Jupyter or Colab environment.

Download Notebook (.ipynb)


Related Tutorial
Data Entry Form using Colab & ipywidgets

Learn how to create interactive data entry forms directly in Google Colab using Python and ipywidgets.

Read Full Tutorial


AI Survey Analysis with Colab

Ask AI for Data Insights from the Stack Overflow Survey

Use Google Colab’s Data Science Agent to explore the Stack Overflow Developer Survey. Just ask questions in plain English — and let the AI write Python code to analyze the data. šŸ“ˆšŸ¤–

Explore Guide

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

šŸŽ„ Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer