Backend Development 6 min read

Building a Python Tkinter GUI to Compare Two Excel Files

This tutorial explains how to set up a Python environment, create a Tkinter graphical interface, and use pandas and openpyxl to let users select and compare two Excel files, displaying any differences directly in the application.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Building a Python Tkinter GUI to Compare Two Excel Files

In data processing and everyday office work, comparing two Excel files is a common need, especially in financial auditing and data quality control. This guide shows how to build a user‑friendly Python application with Tkinter that lets users select Excel files from a local folder and compare their contents.

1. Environment Preparation Ensure Python is installed along with the pandas and openpyxl libraries; Tkinter is bundled with Python. Install missing packages with:

pip install pandas openpyxl

2. Tkinter GUI Design Create a simple window containing labels, entry fields, and buttons for file selection, as well as a text area for results. The following code implements the full GUI and comparison logic:

import tkinter as tk
from tkinter import filedialog
import pandas as pd

# Create main window
root = tk.Tk()
root.title("Excel 数据比较器")

# Variables to store file paths
file_path1 = tk.StringVar()
file_path2 = tk.StringVar()

# Functions to select files
def select_file1():
    path = filedialog.askopenfilename(filetypes=[("Excel 文件", "*.xlsx")])
    file_path1.set(path)

def select_file2():
    path = filedialog.askopenfilename(filetypes=[("Excel 文件", "*.xlsx")])
    file_path2.set(path)

# UI elements
tk.Label(root, text="选择第一个 Excel 文件:").pack()
tk.Entry(root, textvariable=file_path1).pack()
tk.Button(root, text="浏览", command=select_file1).pack()

tk.Label(root, text="选择第二个 Excel 文件:").pack()
tk.Entry(root, textvariable=file_path2).pack()
tk.Button(root, text="浏览", command=select_file2).pack()

# Comparison function
def compare_files():
    result_text.delete(1.0, tk.END)
    result_text.tag_config("red", foreground="red")
    result_text.tag_config("blue", foreground="blue")
    try:
        df1 = pd.read_excel(file_path1.get(), engine='openpyxl')
        df2 = pd.read_excel(file_path2.get(), engine='openpyxl')
    except Exception as e:
        result_text.insert(tk.END, f"读取文件时发生错误:{e}", "red")
        return
    if set(df1.columns) != set(df2.columns):
        result_text.insert(tk.END, "两个文件的列名不匹配。", "red")
        return
    diff_df = pd.DataFrame(columns=df1.columns.tolist() + ["差异"])
    for i, row in df1.iterrows():
        try:
            matched_row = df2.loc[(df2[list(df1.columns)] == row[list(df1.columns)]).all(axis=1)]
            if matched_row.empty:
                diff_df = pd.concat([diff_df, row.to_frame().T])
                diff_df.at[i, "差异"] = "该行在第二个文件中不存在"
            else:
                for col in df1.columns:
                    if row[col] != matched_row.iloc[0][col]:
                        diff_df.at[i, "差异"] = f"列 {col} 的值不同"
                        break
        except Exception as e:
            result_text.insert(tk.END, f"处理数据时发生错误:{e}", "red")
            return
    for i, row in diff_df.iterrows():
        tag = "blue" if row["差异"] == "该行在第二个文件中不存在" else "red"
        result_text.insert(tk.END, row.to_frame().T.to_string(header=False, index=False) + "\n", tag)

tk.Button(root, text="比较文件", command=compare_files).pack()

# Result display area
result_text = tk.Text(root, height=10, width=50)
result_text.pack()

# Run the application
root.mainloop()

3. Run and Test Execute the script; a simple GUI appears, allowing the user to pick two Excel files. Clicking the "比较文件" button reads both files, compares rows and columns, and shows any differences in the text box.

Notes

Both Excel files must share the same column structure; otherwise the comparison will fail.

The current implementation compares all columns. To limit comparison to specific columns, adjust the logic accordingly.

Large Excel files may require noticeable processing time.

By following these steps, you can create a Python‑Tkinter GUI application that enables non‑technical users to select two local Excel files and quickly identify data discrepancies.

GUIPythonExcelpandasTkinterdata-comparison
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.