Visual File Comparator Python GUI

👤 Sharing: AI
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import difflib
import os

class FileComparatorApp:
    def __init__(self, master):
        self.master = master
        master.title("Visual File Comparator")

        self.file1_path = tk.StringVar()
        self.file2_path = tk.StringVar()

        # File 1 selection
        self.file1_label = ttk.Label(master, text="File 1:")
        self.file1_label.grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.file1_entry = ttk.Entry(master, textvariable=self.file1_path, width=50)
        self.file1_entry.grid(row=0, column=1, padx=5, pady=5, sticky="we")
        self.file1_button = ttk.Button(master, text="Browse", command=lambda: self.browse_file(self.file1_path))
        self.file1_button.grid(row=0, column=2, padx=5, pady=5)

        # File 2 selection
        self.file2_label = ttk.Label(master, text="File 2:")
        self.file2_label.grid(row=1, column=0, padx=5, pady=5, sticky="w")
        self.file2_entry = ttk.Entry(master, textvariable=self.file2_path, width=50)
        self.file2_entry.grid(row=1, column=1, padx=5, pady=5, sticky="we")
        self.file2_button = ttk.Button(master, text="Browse", command=lambda: self.browse_file(self.file2_path))
        self.file2_button.grid(row=1, column=2, padx=5, pady=5)

        # Compare button
        self.compare_button = ttk.Button(master, text="Compare", command=self.compare_files)
        self.compare_button.grid(row=2, column=1, padx=5, pady=10)

        # Details button
        self.details_button = ttk.Button(master, text="Details", command=self.show_details)
        self.details_button.grid(row=3, column=1, padx=5, pady=10)

        # Text area for displaying differences
        self.text_area = tk.Text(master, wrap=tk.WORD, height=20, width=80)
        self.text_area.grid(row=4, column=0, columnspan=3, padx=5, pady=5, sticky="nsew")

        # Scrollbar
        self.scrollbar = ttk.Scrollbar(master, command=self.text_area.yview)
        self.scrollbar.grid(row=4, column=3, sticky="ns")
        self.text_area['yscrollcommand'] = self.scrollbar.set

        master.grid_columnconfigure(1, weight=1)
        master.grid_rowconfigure(4, weight=1)

    def browse_file(self, path_variable):
        filename = filedialog.askopenfilename()
        path_variable.set(filename)

    def compare_files(self):
        file1 = self.file1_path.get()
        file2 = self.file2_path.get()

        if not file1 or not file2:
            messagebox.showerror("Error", "Please select both files to compare.")
            return

        try:
            with open(file1, 'r', encoding='utf-8', errors='ignore') as f1, open(file2, 'r', encoding='utf-8', errors='ignore') as f2:
                file1_lines = f1.readlines()
                file2_lines = f2.readlines()

            differ = difflib.Differ()
            diff = list(differ.compare(file1_lines, file2_lines))

            self.text_area.delete("1.0", tk.END)
            for line in diff:
                if line.startswith('+ '):
                    self.text_area.insert(tk.END, line, 'added')
                elif line.startswith('- '):
                    self.text_area.insert(tk.END, line, 'removed')
                elif line.startswith('? '):
                    self.text_area.insert(tk.END, line, 'context')
                else:
                    self.text_area.insert(tk.END, line)

            self.text_area.tag_config('added', background='lightgreen')
            self.text_area.tag_config('removed', background='lightcoral')
            self.text_area.tag_config('context', background='lightyellow')

        except FileNotFoundError:
            messagebox.showerror("Error", "One or both files not found.")
        except Exception as e:
            messagebox.showerror("Error", str(e))

    def show_details(self):
        details_message = """
        Visual File Comparator

        This application allows you to compare two text files and visualize the differences between them.
        It uses the difflib library to generate a line-by-line comparison.

        Key Features:
        - Select files using a browse dialog.
        - Displays added lines in green, removed lines in red, and context lines in yellow.
        - Supports UTF-8 encoding with error handling.
        - Provides a scrollable text area for viewing large differences.

        Usage:
        1. Click the 'Browse' buttons to select the two files you want to compare.
        2. Click the 'Compare' button to generate the comparison.
        3. The differences will be displayed in the text area below.
        """
        messagebox.showinfo("Details", details_message)


root = tk.Tk()
app = FileComparatorApp(root)
root.mainloop()
👁️ Viewed: 5

Comments