This tutorial shows you how to create an intuitive GUI application in Python using Tkinter. The application converts CSV files into JSON or XML format using Pandas. You will also learn how to save files using a file dialog and provide user feedback with interactive labels.
import tkinter as tk # For GUI development
from tkinter import filedialog # For file selection
import pandas as pd # For CSV handling
import xml.etree.ElementTree as ET # For XML conversion
def browse_file():
file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
if file_path:
lbl_message.config(text=f"Selected File: {file_path}", bg="#d1f7c4")
else:
lbl_message.config(text="No file selected.", bg="#f8d7da")
def convert_file():
if not csv_file_path:
lbl_message.config(text="No file selected.", bg="#f8d7da")
return
output_format = option_var.get()
save_path = filedialog.asksaveasfilename(defaultextension=f".{output_format.lower()}",
filetypes=[(f"{output_format} files", f"*.{output_format.lower()}")])
if not save_path:
lbl_message.config(text="Save cancelled.", bg="#fff3cd")
return
try:
df = pd.read_csv(csv_file_path)
if output_format == "JSON":
df.to_json(save_path, orient="records", indent=4)
else:
root = ET.Element("Root")
for _, row in df.iterrows():
row_elem = ET.SubElement(root, "Row")
for col, val in row.items():
ET.SubElement(row_elem, col).text = str(val) if pd.notna(val) else ""
ET.ElementTree(root).write(save_path, encoding="utf-8", xml_declaration=True)
lbl_message.config(text=f"File saved: {save_path}", bg="#d1f7c4")
except Exception as e:
lbl_message.config(text=f"Error: {str(e)}", bg="#f8d7da")
import tkinter as tk
from tkinter import filedialog
import pandas as pd
import xml.etree.ElementTree as ET
import os
# Function to browse and select a CSV file
def browse_file():
global csv_file_path
csv_file_path = filedialog.askopenfilename(
title="Select a CSV File",
filetypes=(("CSV Files", "*.csv"), ("All Files", "*.*"))
)
if csv_file_path:
update_message(f"Selected File: {csv_file_path}", bg="#d1f7c4")
else:
update_message("No file selected. Please select a CSV file.", bg="#f8d7da")
# Function to convert the selected CSV file to JSON or XML
def convert_file():
if not csv_file_path or not os.path.exists(csv_file_path):
update_message("Error: No valid CSV file selected!", bg="#f8d7da")
return
try:
# Read the CSV file into a DataFrame
df = pd.read_csv(csv_file_path)
# Get user choice
choice = option_var.get()
save_path = filedialog.asksaveasfilename(
title=f"Save as {choice}",
defaultextension=f".{choice.lower()}",
filetypes=((f"{choice} Files", f"*.{choice.lower()}"), ("All Files", "*.*"))
)
if not save_path:
update_message("Save operation cancelled.", bg="#fff3cd")
return
if choice == "JSON":
df.to_json(save_path, orient="records", indent=4)
update_message(f"File saved as JSON at {save_path}", bg="#d1f7c4")
elif choice == "XML":
root_element = ET.Element("Root")
for _, row in df.iterrows():
row_element = ET.SubElement(root_element, "Row")
for col_name, value in row.items():
col_element = ET.SubElement(row_element, col_name)
col_element.text = str(value)
tree = ET.ElementTree(root_element)
tree.write(save_path, encoding="utf-8", xml_declaration=True)
update_message(f"File saved as XML at {save_path}", bg="#d1f7c4")
except Exception as e:
update_message(f"Error: {e}", bg="#f8d7da")
# Function to update the message label
def update_message(message, bg="#f0f8ff"):
message_label.config(text=message, bg=bg)
# Main Window
root = tk.Tk()
root.title("CSV to JSON/XML Converter")
# UI Components
tk.Label(root, text="CSV to JSON/XML Converter", font=("Arial", 18, "bold")).pack(pady=10)
message_label = tk.Label(
root, text="Select a CSV file to start.", font=("Arial", 12), bg="#f0f8ff", relief="sunken", width=50
)
message_label.pack(pady=10)
browse_button = tk.Button(root, text="Browse CSV File", command=browse_file)
browse_button.pack(pady=5)
option_var = tk.StringVar(value="JSON")
json_radio = tk.Radiobutton(root, text="Save as JSON", variable=option_var, value="JSON")
json_radio.pack(anchor="w", padx=20)
xml_radio = tk.Radiobutton(root, text="Save as XML", variable=option_var, value="XML")
xml_radio.pack(anchor="w", padx=20)
convert_button = tk.Button(root, text="Convert and Save", command=convert_file)
convert_button.pack(pady=10)
# Global variable for the file path
csv_file_path = None
# Run the application
root.geometry("500x400")
root.mainloop()
elif choice == "XML":
root_element = ET.Element("Root")
for _, row in df.iterrows():
row_element = ET.SubElement(root_element, "Row")
for col_name, value in row.items():
col_element = ET.SubElement(row_element, col_name)
col_element.text = str(value)
tree = ET.ElementTree(root_element)
tree.write(save_path, encoding="utf-8", xml_declaration=True)
update_message(f"File saved as XML at {save_path}", bg="#d1f7c4")
Updated Code Using to_xml()
elif choice == "XML":
df.to_xml(save_path, index=False, root_name="Root", row_name="Row")
update_message(f"File saved as XML at {save_path}", bg="#d1f7c4")
Export SQLite database table data to CSV file by using Dataframe