Create Data Entry Form using ipywidgets in Colab Notebook





Create Data Entry Form in Google Colab using ipywidgets | Python Tutorial #colab


Introduction

Creating an interactive data entry form inside a Google Colab notebook is easy with the help of ipywidgets. This tutorial demonstrates step-by-step how to build a data entry form, capture input data, and download the entries as a CSV file.

Setup and Installation

First, ensure you have ipywidgets installed in your Colab environment:

!pip install ipywidgets
Download sample student.csv file , By using the code given below all rows of data can be removed.
!wget https://www.plus2net.com/python/download/student.csv
import ipywidgets as widgets
from IPython.display import display

# Create input widgets
name_input = widgets.Text(description="Name:")
class_input = widgets.Dropdown(options=["Four", "Five", "Six"],
                    description="Class:") # Changed to Dropdown
mark_input = widgets.IntText(description="Mark:") 
gender_input = widgets.RadioButtons(
    options=["Male", "Female", "Other"], 
    description="Gender:")
add_button = widgets.Button(description="Add Student")

# Arrange widgets in a horizontal layout
form_layout = widgets.HBox([name_input, 
                            class_input, 
                            mark_input,
                            gender_input,
                            add_button])

# Display the form
display(form_layout)
Function to append data and display rows
import pandas as pd
import os
from IPython.display import display, clear_output

def add_student(button):
    """Handles adding a student's details to the CSV file and displays the updated data."""
    name = name_input.value
    student_class = class_input.value
    mark = mark_input.value
    gender = gender_input.value

    file_path = "student.csv"

    # Ensure the file exists with a header if it's being created for the first time
    if not os.path.exists(file_path):
        df = pd.DataFrame(columns=['id', 'name', 'class', 'mark', 'gender'])
        df.to_csv(file_path, index=False)

    # Read the existing data
    df = pd.read_csv(file_path)

    # Filter out rows with missing 'name'
    df.dropna(subset=['name'], inplace=True)

    # Determine the next ID
    next_id = df['id'].max() + 1 if not df.empty else 1

    # Create a new DataFrame for the current student data
    new_student_df = pd.DataFrame([{'id': next_id, 'name': name, 'class': student_class, 
                                    'mark': mark, 'gender': gender}])

    # Append the new student data to the existing data
    df = pd.concat([df, new_student_df], ignore_index=True)

    # Write the updated DataFrame back to the CSV file
    df.to_csv(file_path, mode='w', header=True, index=False)

    # Clear the input fields
    name_input.value = ""
    class_input.value = "Four" # Reset to default
    mark_input.value = 0
    gender_input.value = "Male"

    # Read and display the updated CSV
    clear_output(wait=True)
    updated_df = pd.read_csv(file_path)
    updated_df.dropna(subset=['name'], inplace=True)

    display(form_layout)
    display(updated_df)

# Link the function to the button's on_click event
add_button.on_click(add_student)
Display all records from the student ( student.csv ) file.
# Read and print the raw content of the CSV file
try:
    with open("student.csv", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("student.csv not found. Please add some data using the form first.")
Delete all rows of data from CSV file.
import pandas as pd
import os

file_path = "student.csv"

if os.path.exists(file_path):
    # Read the header
    df = pd.read_csv(file_path)
    # Create an empty DataFrame with the same columns
    empty_df = pd.DataFrame(columns=df.columns)
    # Write the empty DataFrame back to the CSV, keeping the header
    empty_df.to_csv(file_path, mode='w', header=True, index=False)
    print(f"All data rows deleted from {file_path}. The header remains.")
else:
    print(f"{file_path} not found. No data to delete.")
Allow file download to local system.
from google.colab import files
files.download('student.csv')

Conclusion

With just a few lines of code, we created a fully functional data entry form inside Google Colab using ipywidgets. This approach is ideal for collecting structured data during interactive sessions or demonstrations. The collected data can easily be downloaded in CSV format for further processing.

Read More about ipywidgets in Jupyter Notebooks


Learn more about Google Colab platform »


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