Build a File Manager in Python with GUI

Tech Orcus
By -
11 minute read
0

File manager Using Python

Looking for a beginner-friendly Python project to improve your skills? In this guide, we will create a simple File Manager using Python's GUI library, Tkinter. A File Manager lets you browse files, open them, and delete or rename them. Let’s get started!

Step 1:

To install the necessary files, run the following command in your terminal:

pip install tkinter
Install Required Libraries

Before diving into the code, ensure you have Python installed on your computer. If not, check out our Python installation guide. We will use the Tkinter library for the GUI, which comes pre-installed with Python.

Installing Additional Libraries

For advanced functionalities, you might need the os and shutil libraries. These libraries are included in Python by default, so no extra installation is required.

Step 2: Import Libraries

Start by importing the necessary libraries:

import os
import shutil
from tkinter import Tk, Label, Button, filedialog, messagebox
        

Step 3: Create the GUI

We will create a window with buttons to perform file management tasks.

# Initialize the main window
root = Tk()
root.title("Python File Manager")
root.geometry("400x300")
        

Step 4: Add File Management Functions

1. Browse and Open Files

def open_file():
    file_path = filedialog.askopenfilename()
    if file_path:
        os.startfile(file_path)
        

2. Delete a File

def delete_file():
    file_path = filedialog.askopenfilename()
    if file_path:
        os.remove(file_path)
        messagebox.showinfo("Success", "File Deleted Successfully")
        

3. Rename a File

def rename_file():
    file_path = filedialog.askopenfilename()
    if file_path:
        new_name = filedialog.asksaveasfilename()
        if new_name:
            os.rename(file_path, new_name)
            messagebox.showinfo("Success", "File Renamed Successfully")
        

Step 5: Add Buttons to the GUI

Let’s add buttons for each functionality:

# Add buttons to the GUI
Label(root, text="File Manager", font=("Helvetica", 16)).pack(pady=10)

Button(root, text="Open File", command=open_file).pack(pady=5)
Button(root, text="Delete File", command=delete_file).pack(pady=5)
Button(root, text="Rename File", command=rename_file).pack(pady=5)

root.mainloop()
        

So now complete code will look like this.

# Import required libraries
import os
import shutil
from tkinter import Tk, Label, Button, filedialog, messagebox

# Function to open a file
def open_file():
    file_path = filedialog.askopenfilename()
    if file_path:
        os.startfile(file_path)

# Function to delete a file
def delete_file():
    file_path = filedialog.askopenfilename()
    if file_path:
        os.remove(file_path)
        messagebox.showinfo("Success", "File Deleted Successfully")

# Function to rename a file
def rename_file():
    file_path = filedialog.askopenfilename()
    if file_path:
        new_name = filedialog.asksaveasfilename()
        if new_name:
            os.rename(file_path, new_name)
            messagebox.showinfo("Success", "File Renamed Successfully")

# Initialize the main window
root = Tk()
root.title("Python File Manager")
root.geometry("400x300")

# Add buttons to the GUI
Label(root, text="File Manager", font=("Helvetica", 16)).pack(pady=10)
Button(root, text="Open File", command=open_file).pack(pady=5)
Button(root, text="Delete File", command=delete_file).pack(pady=5)
Button(root, text="Rename File", command=rename_file).pack(pady=5)

# Run the application
root.mainloop()



Edit:- Now For more good Features i have added certain scripts. Scroll at bottom for complete Script.
This script significantly enhances the original image duplicate finder by implementing several new features to improve user experience, functionality, and performance:

Key Changes Made:

  • Adjustable Threshold: Users can now set the similarity threshold dynamically using a slider, making it easier to fine-tune the detection of similar images. For example, the threshold slider is created using: tk.Scale(root, from_=1, to=20, orient="horizontal", variable=threshold_var)
  • Preview and Safe Deletion: Instead of deleting images directly, similar images are moved to a temporary folder named Duplicate_Temp, allowing users to review them later. This is handled using: shutil.move(file_path, temp_folder)
  • Subfolder Support: A checkbox lets users choose whether to include images in subfolders during the analysis. This is enabled using: os.walk(folder_path)
  • Multithreading: To prevent the GUI from freezing during image processing, the analysis runs in a separate thread: threading.Thread(target=analyze_image, args=(...)).start()
  • Logging Panel: A text area has been added to display logs for every action, such as moving files or encountering errors. Logs are updated using: log_text.insert(tk.END, "Log message")

Overview of the Script:

The script uses Python's tkinter library for the GUI and integrates image hashing with the imagehash library for similarity comparison. The main functions are:

  • get_image_hash: Computes the hash of an image using average hashing from the PIL.Image module.
  • find_similar_images: Iterates through the selected folder (and subfolders, if enabled), compares each image's hash with the target image, and moves similar images to a temporary folder.
  • analyze_image: Manages the overall analysis, including logging results and displaying a summary to the user.
  • create_gui: Builds the user interface, allowing users to select the image, folder, threshold, and other options. It also links UI elements to the corresponding functions.

Overall, these changes improve the script's usability, flexibility, and safety, making it suitable for a broader range of use cases. The GUI enhancements ensure that users have full control over the process while maintaining a clean and responsive interface.


Complete Edit 1 Script:-


import tkinter as tk from tkinter import filedialog, messagebox, ttk import os from PIL import Image import imagehash import threading import shutil # Function to calculate the hash of an image def get_image_hash(image_path): try: image = Image.open(image_path) return imagehash.average_hash(image) except Exception as e: print(f"Error hashing image {image_path}: {e}") return None # Function to find similar images and move them to a temporary folder def find_similar_images(image_path, folder_path, threshold, include_subfolders, log_text): target_image_hash = get_image_hash(image_path) if target_image_hash is None: messagebox.showerror("Error", "Failed to calculate hash for the target image.") return [] temp_folder = os.path.join(folder_path, "Duplicate_Temp") os.makedirs(temp_folder, exist_ok=True) files = [] if include_subfolders: for root, _, filenames in os.walk(folder_path): files.extend([os.path.join(root, file) for file in filenames]) else: files = [os.path.join(folder_path, file) for file in os.listdir(folder_path)] similar_images = [] for file_path in files: if os.path.isfile(file_path) and file_path.lower().endswith((".jpg", ".jpeg", ".png", ".gif")): current_image_hash = get_image_hash(file_path) if current_image_hash and target_image_hash - current_image_hash < threshold: similar_images.append(file_path) try: shutil.move(file_path, temp_folder) log_text.insert(tk.END, f"Moved similar image: {file_path}\n") except Exception as e: log_text.insert(tk.END, f"Error moving {file_path}: {e}\n") return similar_images # Function to handle the analysis process def analyze_image(image_path, folder_path, threshold, include_subfolders, log_text): log_text.delete(1.0, tk.END) similar_images = find_similar_images(image_path, folder_path, threshold, include_subfolders, log_text) if similar_images: result_message = f"Found {len(similar_images)} similar images. Moved to temporary folder." messagebox.showinfo("Result", result_message) else: messagebox.showinfo("Result", "No similar images found.") # Function to handle GUI inputs and multithreading def start_analysis(image_path_var, folder_path_var, threshold_var, include_subfolders_var, log_text): image_path = image_path_var.get() folder_path = folder_path_var.get() threshold = int(threshold_var.get()) include_subfolders = include_subfolders_var.get() if not image_path or not folder_path: messagebox.showerror("Error", "Image and folder paths must be selected.") return threading.Thread( target=analyze_image, args=(image_path, folder_path, threshold, include_subfolders, log_text), ).start() # Function to create the GUI def create_gui(): root = tk.Tk() root.title("Enhanced Image Duplicate Finder") tk.Label(root, text="Select Image:").grid(row=0, column=0, padx=10, pady=10, sticky="w") image_path_var = tk.StringVar() tk.Entry(root, textvariable=image_path_var, width=50).grid(row=0, column=1, padx=10) tk.Button(root, text="Browse", command=lambda: image_path_var.set(filedialog.askopenfilename(filetypes=[("Image Files", "*.jpg *.jpeg *.png *.gif")]))) .grid(row=0, column=2, padx=10) tk.Label(root, text="Select Folder:").grid(row=1, column=0, padx=10, pady=10, sticky="w") folder_path_var = tk.StringVar() tk.Entry(root, textvariable=folder_path_var, width=50).grid(row=1, column=1, padx=10) tk.Button(root, text="Browse", command=lambda: folder_path_var.set(filedialog.askdirectory())).grid(row=1, column=2, padx=10) tk.Label(root, text="Similarity Threshold:").grid(row=2, column=0, padx=10, pady=10, sticky="w") threshold_var = tk.StringVar(value="5") tk.Scale(root, from_=1, to=20, orient="horizontal", variable=threshold_var).grid(row=2, column=1, padx=10, pady=10, sticky="w") include_subfolders_var = tk.BooleanVar() tk.Checkbutton(root, text="Include Subfolders", variable=include_subfolders_var).grid(row=3, column=1, padx=10, pady=10, sticky="w") log_text = tk.Text(root, width=80, height=20) log_text.grid(row=4, column=0, columnspan=3, padx=10, pady=10) tk.Button( root, text="Start Analysis", command=lambda: start_analysis(image_path_var, folder_path_var, threshold_var, include_subfolders_var, log_text), bg="lightblue", font=("Arial", 12), ).grid(row=5, column=0, columnspan=3, pady=20) root.mainloop() create_gui()


Conclusion

With this project, you’ve learned how to create a simple File Manager in Python using Tkinter. This project not only improves your Python skills but also helps you understand GUI programming and file handling. Try adding more features like copying files or creating new folders to make your File Manager even better!

Post a Comment

0Comments

Post a Comment (0)
Today | 14, April 2025