Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

make a tkinter py script that does this 1. it has a textinput for multiline text 2. it…

  1. User

    make a tkinter py script that does this

    1. it has a textinput for multiline text
    2. it has a button
    3. it has a table that shows the results

    input should follow this format, if not then report error when pressing the button:

    file/to/path/file
    another/path
    

    when button is pressed, for each path it analyzes for duplicated files with different numbered suffix

    if path is path/to/file, it will look for sequence path/to/file(<index>) if path is path/to/file(1), it will look for base path/to/file and sequence path/to/file(<index>) if path is path/to/file(2), it will look for base path/to/file, and sequence path/to/file(<index>) with extension, if path is path/to/file(1).pdf, it will look for base path/to/file.pdf and nearby sequence path/to/file(<index>).pdf you get what i mean

    given a path, you get a list of all sibling files, then for each file except the file, you search for file(<index>) or file(<index>)<extension if exists>. <index> starts from 0 to 999 (4 digits could be year number so)

    then for the table widget, it is two column, file path and duplicate list string duplicate list string is in comma-separated list of dups: <base>,[<index>,]+ lets say path is path/to/file, then if it finds (1), (22), the dup string is 1,22 if path is path/to/file(1).pdf, and it finds path/to/file.pdf, and path/to/file(2).pdf, then dup string is base,2

    if we double click a row, it will open the folder and point to the file (in windows its the explorer and highlight the file item)

  2. Assistant

    Sure! Below is a complete Python script using tkinter that fulfills your requirements. This script provides a GUI with a multiline text input, a button to process the input paths, and a table displaying the results. It also handles double-click events on the table rows to open the specified file in Windows Explorer.

    Prerequisites:

    • Ensure you're running this script on a Windows machine, as it uses explorer to open files.
    • Python installed with tkinter support (usually included by default).

    Script Overview:

    1. GUI Components:
      • Text Input: For entering multiple file paths, each on a new line.
      • Button: When clicked, it processes the input paths.
      • Treeview Table: Displays the results with two columns: "File Path" and "Duplicate List".
    2. Functionality:
      • Input Validation: Ensures each entered path exists. If any path is invalid, an error is shown.
      • Duplicate Analysis: For each valid path, the script searches for duplicates following the specified naming patterns.
      • Result Display: Shows the original file path and its duplicates in the table.
      • Double-Click Action: Opens the file location in Windows Explorer and highlights the specific file.

    Complete Script:

    import tkinter as tk
    from tkinter import ttk, messagebox
    import os
    import re
    import subprocess
    
    class DuplicateFinderApp(tk.Tk):
        def __init__(self):
            super().__init__()
            self.title("Duplicate File Finder")
            self.geometry("800x600")
            self.create_widgets()
    
        def create_widgets(self):
            # Frame for input and button
            input_frame = ttk.Frame(self)
            input_frame.pack(fill=tk.BOTH, expand=False, padx=10, pady=10)
    
            # Label for input
            input_label = ttk.Label(input_frame, text="Enter file paths (one per line):")
            input_label.pack(anchor=tk.W)
    
            # Text widget for multiline input
            self.text_input = tk.Text(input_frame, height=10)
            self.text_input.pack(fill=tk.BOTH, expand=True, pady=5)
    
            # Button to process input
            process_button = ttk.Button(input_frame, text="Find Duplicates", command=self.process_paths)
            process_button.pack(pady=5)
    
            # Separator
            separator = ttk.Separator(self, orient='horizontal')
            separator.pack(fill=tk.X, padx=10, pady=10)
    
            # Frame for the table
            table_frame = ttk.Frame(self)
            table_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
    
            # Define columns
            columns = ("file_path", "dup_list")
            self.tree = ttk.Treeview(table_frame, columns=columns, show='headings')
            self.tree.heading("file_path", text="File Path")
            self.tree.heading("dup_list", text="Duplicate List")
            self.tree.column("file_path", width=500)
            self.tree.column("dup_list", width=250)
            self.tree.pack(fill=tk.BOTH, expand=True)
    
            # Bind double-click event
            self.tree.bind("<Double-1>", self.on_row_double_click)
    
            # Add scrollbar
            scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=self.tree.yview)
            self.tree.configure(yscroll=scrollbar.set)
            scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    
        def parse_filename(self, filename):
            """
            Parses the filename into base, index (if any), and extension.
            Returns a tuple: (base, index, extension)
            """
            pattern = re.compile(r'^(?P<base>.+?)(?:\((?P<index>\d{1,3})\))?(?P<ext>\.[^.]+)?$')
            match = pattern.match(filename)
            if match:
                base = match.group('base')
                index = match.group('index')
                ext = match.group('ext') if match.group('ext') else ''
                return base, index, ext
            else:
                return filename, None, ''
    
        def process_paths(self):
            """
            Callback for the 'Find Duplicates' button.
            """
            # Clear existing table entries
            for item in self.tree.get_children():
                self.tree.delete(item)
    
            # Get input paths
            input_text = self.text_input.get("1.0", tk.END)
            paths = [line.strip() for line in input_text.strip().splitlines() if line.strip()]
    
            if not paths:
                messagebox.showerror("Input Error", "Please enter at least one file path.")
                return
    
            # Validate all paths
            invalid_paths = [path for path in paths if not os.path.exists(path)]
            if invalid_paths:
                message = "The following paths do not exist:\n" + "\n".join(invalid_paths)
                messagebox.showerror("Invalid Paths", message)
                return
    
            # Process each path
            for path in paths:
                dup_str = self.get_duplicate_string(path)
                self.tree.insert("", tk.END, values=(path, dup_str))
    
            messagebox.showinfo("Processing Complete", "Duplicate analysis completed.")
    
        def get_duplicate_string(self, path):
            """
            Given a file path, returns the duplicate list string as specified.
            """
            directory, filename = os.path.split(path)
            base, index, ext = self.parse_filename(filename)
    
            if index:
                base_filename = f"{base}{ext}"
            else:
                base_filename = filename
    
            # List all files in the directory
            try:
                siblings = os.listdir(directory)
            except Exception as e:
                return "Error reading directory"
    
            duplicates = []
            indices = []
    
            # If input has index, check if base file exists
            if index:
                if base_filename in siblings:
                    duplicates.append("base")
    
            # Pattern to match duplicates
            # Escape base to handle any special characters
            escaped_base = re.escape(base)
            ext_pattern = re.escape(ext)
            dup_pattern = re.compile(rf'^{escaped_base}\((\d{{1,3}})\){ext_pattern}$')
    
            for sibling in siblings:
                if sibling == filename:
                    continue  # Skip the input file itself
    
                match = dup_pattern.match(sibling)
                if match:
                    dup_index = match.group(1).lstrip('0') or '0'  # Remove leading zeros
                    if dup_index.isdigit():
                        dup_index_int = int(dup_index)
                        if 0 <= dup_index_int <= 999:
                            indices.append(str(dup_index_int))
    
            # Sort indices numerically and remove duplicates
            unique_sorted_indices = sorted(set(indices), key=lambda x: int(x))
    
            if index:
                if unique_sorted_indices:
                    duplicates.append(",".join(unique_sorted_indices))
            else:
                duplicates = unique_sorted_indices
    
            dup_list_str = ",".join(duplicates) if duplicates else "None"
            return dup_list_str
    
        def on_row_double_click(self, event):
            """
            Callback for double-clicking a table row.
            Opens the file location in Windows Explorer and selects the file.
            """
            selected_item = self.tree.selection()
            if not selected_item:
                return
            item = selected_item[0]
            file_path = self.tree.item(item, "values")[0]
            if os.path.exists(file_path):
                # Use explorer to select the file
                try:
                    subprocess.run(['explorer', '/select,', os.path.normpath(file_path)])
                except Exception as e:
                    messagebox.showerror("Error", f"Could not open file location.\n{e}")
            else:
                messagebox.showerror("File Not Found", f"The file does not exist:\n{file_path}")
    
    if __name__ == "__main__":
        app = DuplicateFinderApp()
        app.mainloop()
    

    How to Use the Script:

    1. Run the Script:

      • Save the script to a file, for example, duplicate_finder.py.
      • Open Command Prompt and navigate to the directory containing the script.
      • Run the script using python duplicate_finder.py.
    2. Enter File Paths:

      • In the application window, enter one or more file paths, each on a new line, following the specified format. For example:
        C:\Users\Username\Documents\file.txt
        D:\Projects\another_file(1).pdf
        
      • Ensure that the paths entered actually exist on your system.
    3. Find Duplicates:

      • Click the "Find Duplicates" button.
      • The application will analyze each path and display the results in the table below.
    4. View Duplicates:

      • The table shows each original file path and its corresponding duplicates.
      • If duplicates are found, they are listed as per your specified format (e.g., 1,22 or base,2).
    5. Open File Location:

      • To quickly navigate to a file, double-click on its row in the table.
      • This will open Windows Explorer and highlight the selected file.

    Notes:

    • Error Handling:

      • If any entered path does not exist, an error message will be displayed, and the processing will halt.
      • Ensure all paths are correct and accessible.
    • Duplicate Logic:

      • The script uses regex to parse filenames and identify duplicates based on the presence of numbered suffixes.
      • It handles files with and without extensions appropriately.
    • Customization:

      • You can modify the script to change the range of indices or adapt it for different naming conventions as needed.

    This script should meet all the requirements you've specified, providing a user-friendly interface for finding duplicate files based on numbered suffixes.