Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Tkinter – How to export data from Entry Fields to a CSV file?
The Entry widget in Tkinter allows users to input single-line text. You can export data from multiple Entry fields to a CSV file using Python's built-in csv module. This is useful for creating data entry forms that save user information to spreadsheet files.
Creating the Data Entry Interface
We'll create a simple form with name, age, and contact fields, along with buttons to add, save, and clear data ?
# Import the required libraries
import csv
import tkinter as tk
from tkinter import messagebox
# Create main window
window = tk.Tk()
window.title("Data Entry")
window.geometry("400x300")
# List to store all entries
main_list = []
def add_data():
"""Add current entry data to the list"""
entry_data = [name_entry.get(), age_entry.get(), contact_entry.get()]
main_list.append(entry_data)
messagebox.showinfo("Information", "Data has been added successfully!")
def save_to_csv():
"""Save all data to CSV file"""
with open("data_entry.csv", "w", newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerow(["Name", "Age", "Contact"]) # Header row
csv_writer.writerows(main_list)
messagebox.showinfo("Information", "Data saved to CSV successfully!")
def clear_fields():
"""Clear all entry fields"""
name_entry.delete(0, tk.END)
age_entry.delete(0, tk.END)
contact_entry.delete(0, tk.END)
# Create labels and entry fields
tk.Label(window, text="Name:", padx=10, pady=5).grid(row=0, column=0, sticky="w")
tk.Label(window, text="Age:", padx=10, pady=5).grid(row=1, column=0, sticky="w")
tk.Label(window, text="Contact:", padx=10, pady=5).grid(row=2, column=0, sticky="w")
name_entry = tk.Entry(window, width=25, borderwidth=2)
age_entry = tk.Entry(window, width=25, borderwidth=2)
contact_entry = tk.Entry(window, width=25, borderwidth=2)
name_entry.grid(row=0, column=1, padx=10, pady=5)
age_entry.grid(row=1, column=1, padx=10, pady=5)
contact_entry.grid(row=2, column=1, padx=10, pady=5)
# Create buttons
tk.Button(window, text="Add", width=15, command=add_data).grid(row=3, column=0, columnspan=2, pady=10)
tk.Button(window, text="Save to CSV", width=15, command=save_to_csv).grid(row=4, column=0, columnspan=2, pady=5)
tk.Button(window, text="Clear", width=15, command=clear_fields).grid(row=5, column=0, columnspan=2, pady=5)
tk.Button(window, text="Exit", width=15, command=window.quit).grid(row=6, column=0, columnspan=2, pady=5)
window.mainloop()
How It Works
The application works in three main steps:
- Add: Collects data from Entry widgets and stores it in a list
- Save: Writes the collected data to a CSV file with headers
- Clear: Removes text from all Entry fields
Sample CSV Output
After entering data and clicking "Save to CSV", the generated file will look like this ?
Name,Age,Contact John Doe,25,1234567890 Jane Smith,30,9876543210 Bob Wilson,28,5555551234
Key Features
- Data Collection: Entry widgets capture user input
- Temporary Storage: Data is stored in a list before saving
-
CSV Export: Uses the
csv.writer()method for proper formatting - User Feedback: Message boxes confirm successful operations
Enhanced Version with Error Handling
import csv
import tkinter as tk
from tkinter import messagebox
def create_data_entry_app():
window = tk.Tk()
window.title("Data Entry to CSV")
window.geometry("400x300")
data_storage = []
def add_entry():
name = name_var.get().strip()
age = age_var.get().strip()
contact = contact_var.get().strip()
# Validate input
if not all([name, age, contact]):
messagebox.showwarning("Warning", "Please fill all fields!")
return
try:
int(age) # Validate age is numeric
data_storage.append([name, age, contact])
messagebox.showinfo("Success", f"Added: {name}")
clear_entries()
except ValueError:
messagebox.showerror("Error", "Age must be a number!")
def save_data():
if not data_storage:
messagebox.showwarning("Warning", "No data to save!")
return
try:
with open("contacts.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "Contact"])
writer.writerows(data_storage)
messagebox.showinfo("Success", f"Saved {len(data_storage)} records!")
except Exception as e:
messagebox.showerror("Error", f"Failed to save: {e}")
def clear_entries():
name_var.set("")
age_var.set("")
contact_var.set("")
# Variables for entry fields
name_var = tk.StringVar()
age_var = tk.StringVar()
contact_var = tk.StringVar()
# Create interface
tk.Label(window, text="Name:").grid(row=0, column=0, sticky="w", padx=10, pady=5)
tk.Entry(window, textvariable=name_var, width=25).grid(row=0, column=1, padx=10, pady=5)
tk.Label(window, text="Age:").grid(row=1, column=0, sticky="w", padx=10, pady=5)
tk.Entry(window, textvariable=age_var, width=25).grid(row=1, column=1, padx=10, pady=5)
tk.Label(window, text="Contact:").grid(row=2, column=0, sticky="w", padx=10, pady=5)
tk.Entry(window, textvariable=contact_var, width=25).grid(row=2, column=1, padx=10, pady=5)
tk.Button(window, text="Add Entry", command=add_entry).grid(row=3, column=0, columnspan=2, pady=10)
tk.Button(window, text="Save to CSV", command=save_data).grid(row=4, column=0, columnspan=2, pady=5)
tk.Button(window, text="Clear", command=clear_entries).grid(row=5, column=0, columnspan=2, pady=5)
window.mainloop()
# Run the application
create_data_entry_app()
Conclusion
Exporting Entry field data to CSV involves collecting user input, storing it temporarily, and using Python's csv module to write formatted files. Add validation and error handling for a more robust application.
