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
How to make a button open a specific .csv file using Python Tkinter?
Graphical User Interfaces (GUIs) make it easy to use computer programs. Python's Tkinter library provides a simple way to create desktop applications. In this article, we'll explore how to create a button that opens and displays CSV files using Python Tkinter.
Application Overview
Our application will include the following components ?
Main Window ? The application's primary interface
Open Button ? Triggers file selection dialog
File Dialog ? Allows users to browse and select CSV files
Display Area ? Shows CSV content in a readable format
Method 1: Display CSV in Console
This approach prints CSV data to the console when a file is selected ?
import tkinter as tk
from tkinter import filedialog, messagebox
import csv
def open_csv_file():
file_path = filedialog.askopenfilename(
title="Select CSV File",
defaultextension=".csv",
filetypes=[("CSV Files", "*.csv"), ("All Files", "*.*")]
)
if file_path:
try:
with open(file_path, "r", newline='', encoding='utf-8') as csv_file:
csv_reader = csv.reader(csv_file)
print(f"Contents of {file_path}:")
print("-" * 50)
for row_num, row in enumerate(csv_reader, 1):
print(f"Row {row_num}: {row}")
except Exception as e:
messagebox.showerror("Error", f"Failed to open file: {e}")
# Create main window
root = tk.Tk()
root.title("CSV File Opener")
root.geometry("300x150")
# Create and pack button
open_button = tk.Button(
root,
text="Open CSV File",
command=open_csv_file,
font=("Arial", 12),
bg="#4CAF50",
fg="white",
padx=20,
pady=10
)
open_button.pack(expand=True)
root.mainloop()
Method 2: Display CSV in GUI Window
This approach creates a scrollable text widget to display CSV content within the application ?
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import csv
class CSVViewer:
def __init__(self, root):
self.root = root
self.root.title("CSV File Viewer")
self.root.geometry("600x400")
# Create button frame
button_frame = tk.Frame(root)
button_frame.pack(pady=10)
# Open button
self.open_button = tk.Button(
button_frame,
text="Open CSV File",
command=self.open_csv_file,
font=("Arial", 12),
bg="#2196F3",
fg="white",
padx=20,
pady=5
)
self.open_button.pack()
# Text area for displaying CSV content
self.text_area = scrolledtext.ScrolledText(
root,
wrap=tk.NONE,
font=("Courier", 10),
height=20,
width=70
)
self.text_area.pack(expand=True, fill='both', padx=10, pady=10)
def open_csv_file(self):
file_path = filedialog.askopenfilename(
title="Select CSV File",
defaultextension=".csv",
filetypes=[("CSV Files", "*.csv"), ("All Files", "*.*")]
)
if file_path:
try:
# Clear previous content
self.text_area.delete(1.0, tk.END)
with open(file_path, "r", newline='', encoding='utf-8') as csv_file:
csv_reader = csv.reader(csv_file)
# Display filename
self.text_area.insert(tk.END, f"File: {file_path}\n")
self.text_area.insert(tk.END, "=" * 60 + "\n\n")
# Display CSV content with row numbers
for row_num, row in enumerate(csv_reader, 1):
formatted_row = " | ".join(str(cell) for cell in row)
self.text_area.insert(tk.END, f"Row {row_num:3d}: {formatted_row}\n")
except Exception as e:
messagebox.showerror("Error", f"Failed to open file: {e}")
# Create and run application
root = tk.Tk()
app = CSVViewer(root)
root.mainloop()
Key Features Explained
Both implementations include several important features ?
File Dialog ?
filedialog.askopenfilename()creates a standard file selection dialogError Handling ? Try-except blocks catch file reading errors
CSV Reading ?
csv.reader()properly handles CSV formattingEncoding Support ? UTF-8 encoding ensures proper character display
Comparison
| Method | Display Location | Best For | User Experience |
|---|---|---|---|
| Console Output | Terminal/Console | Simple debugging | Basic |
| GUI Text Widget | Application window | User-friendly apps | Professional |
Conclusion
Creating a CSV file opener with Tkinter involves combining file dialogs, CSV reading, and GUI components. The GUI-based approach provides a better user experience, while console output works well for simple applications.
