Make a tinker pygui that allows me to select a folder and then say a folder has 16 ecterara the first number only then list all the numbers no duplicates in a list
Assistant
Sure! Below is a Python script using the tkinter library to create a GUI application that allows you to:
Select a Folder: Browse and select a target directory.
Process Folder Names: Scan the selected directory's subfolders, extract the first number that appears between underscores in each folder name.
Display Unique Numbers: List all unique numbers extracted from the folder names in a listbox.
Prerequisites
Python Installed: Ensure you have Python installed on your system.
Tkinter Library: tkinter comes pre-installed with Python. No additional installation is required.
Step-by-Step Guide
Import Necessary Libraries:
tkinter: For creating the GUI.
tkinter.filedialog: To open the folder selection dialog.
re: For regular expressions to extract numbers.
os: To interact with the operating system's directory structure.
Create the GUI Layout:
A button to select the folder.
A listbox to display the unique numbers.
A scrollbar for the listbox in case of many numbers.
Define Functionality:
Select Folder: Opens a dialog to select the folder and processes the folder names.
Extract Numbers: Uses a regular expression to find the first number between underscores in each folder name.
Display Results: Shows the unique numbers in the listbox.
Complete Python Script
python
import tkinter as tk
from tkinter import filedialog, messagebox
import os
import re
def select_folder():
folder_path = filedialog.askdirectory()
if folder_path:
numbers = extract_numbers(folder_path)
if numbers:
display_numbers(numbers)
else:
messagebox.showinfo("No Numbers Found", "No matching numbers were found in the folder names.")
def extract_numbers(folder_path):
# Regular expression to find the first number between underscores
pattern = re.compile(r'_(\d+)_')
unique_numbers = set()
try:
for entry in os.listdir(folder_path):
entry_path = os.path.join(folder_path, entry)
if os.path.isdir(entry_path):
match = pattern.search(entry)
if match:
number = match.group(1)
unique_numbers.add(number)
except Exception as e:
messagebox.showerror("Error", f"An error occurred while processing folders:\n{e}")
# Sort the numbers numerically
sorted_numbers = sorted(unique_numbers, key=lambda x: int(x))
return sorted_numbers
def display_numbers(numbers):
listbox.delete(0, tk.END) # Clear existing items
for number in numbers:
listbox.insert(tk.END, number)
# Initialize the main application window
root = tk.Tk()
root.title("Folder Number Extractor")
root.geometry("400x400")
root.resizable(False, False)
# Create and place the "Select Folder" button
select_button = tk.Button(root, text="Select Folder", command=select_folder, width=20, height=2)
select_button.pack(pady=20)
# Label for the listbox
list_label = tk.Label(root, text="Unique Numbers Found:")
list_label.pack()
# Create a frame for the listbox and scrollbar
list_frame = tk.Frame(root)
list_frame.pack(pady=10, fill=tk.BOTH, expand=True)
# Add a scrollbar to the listbox
scrollbar = tk.Scrollbar(list_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Create and place the listbox
listbox = tk.Listbox(list_frame, yscrollcommand=scrollbar.set, font=("Arial", 12))
listbox.pack(fill=tk.BOTH, expand=True)
scrollbar.config(command=listbox.yview)
# Run the application
root.mainloop()
Explanation of the Script
Function select_folder:
Opens a dialog for the user to select a directory.
Calls extract_numbers to process the folder names.
Displays the results using display_numbers.
Function extract_numbers:
Uses a regular expression _(\d+)_ to find patterns like _16_ in folder names.
Iterates through each subfolder in the selected directory.
Extracts the first number between underscores and adds it to a set to ensure uniqueness.
Sorts the numbers numerically before returning.
Function display_numbers:
Clears any existing items in the listbox.
Inserts the unique numbers into the listbox for display.
GUI Setup:
The main window is set with a fixed size and title.
A button is provided to initiate folder selection.
A listbox displays the unique numbers with an associated scrollbar.
How to Use
Run the Script: Save the script to a file, e.g., folder_number_extractor.py, and run it using Python:
bash
python folder_number_extractor.py
Select Folder: Click the "Select Folder" button and navigate to the directory you want to scan.
View Results: After selecting the folder, the application will display all unique numbers extracted from the folder names in the listbox.
Notes
Folder Name Pattern: The script looks for numbers that are enclosed by underscores. For example, in example_16_test, it will extract 16. Ensure your folder names follow this pattern or adjust the regular expression accordingly.
Error Handling: The script includes basic error handling to notify you if something goes wrong during folder processing.
Customization: You can modify the regular expression in the extract_numbers function to fit different folder naming conventions as needed.
Conclusion
This script provides a simple and effective way to extract unique numbers from folder names using a graphical interface. You can further enhance it by adding features like exporting the numbers to a file or handling different naming patterns based on your requirements.