The error message you're encountering—"path is used prior to global declaration"—is typically caused by attempting to modify a global variable within a function without properly declaring it as global before its first use in that function. In Python, when you want to modify a global variable inside a function, you must declare it as global at the very beginning of the function, before any operations on that variable.
Let's identify and correct the specific issues in your code.
Understanding the Issue
Problematic Function: select_output_folder
Here's the problematic part of your select_output_folder function:
def select_output_folder():
"""Allow user to select an output folder and set the output_folder_var."""
folder = filedialog.askdirectory(title="Select Output Folder")
if folder:
output_folder_var.set(folder)
global output_folder
output_folder = folder
# Update UI elements that display the output folder
if 'output_label' in globals():
output_label.config(text=folder)
else:
global output_label
output_label = tb.Label(root, text=f"Output Folder: {folder}")
output_label.pack(pady=5)
Issue Explanation
-
Order of global Declaration:
- Incorrect: You are using
output_folder_var.set(folder) before declaring global output_folder.
- In Python, the
global statement must come before any use of the global variable within the function.
-
Redundant Global Variables:
- You have both
output_folder_var (a StringVar) and output_folder (a separate global variable) managing the output folder path. This can lead to inconsistencies and confusion.
Step-by-Step Solution
1. Move global Declarations to the Top
Ensure that all global declarations are at the very beginning of the function, before any operations on the global variables.
2. Consolidate Output Folder Management
Consider using only output_folder_var (the StringVar) to manage the output folder path. This simplifies the code and reduces the need for multiple global variables.
3. Updated select_output_folder Function
Here's the corrected and optimized version of your select_output_folder function:
def select_output_folder():
"""Allow user to select an output folder and set the output_folder_var."""
global output_folder # Move global declarations to the top
global output_label
folder = filedialog.askdirectory(title="Select Output Folder")
if folder:
output_folder_var.set(folder)
output_folder = folder # Now safe to modify after declaring global
# Update UI elements that display the output folder
if 'output_label' in globals():
output_label.config(text=f"Output Folder: {folder}")
else:
output_label = tb.Label(root, text=f"Output Folder: {folder}")
output_label.pack(pady=5)
4. Review Other Functions for Similar Issues
Check other functions in your code to ensure that any modifications to global variables are preceded by a global declaration at the start of the function. Here's an example:
Original set_disk_threshold Function:
def set_disk_threshold():
"""Set the disk space threshold for auto-pausing."""
try:
value = int(disk_threshold_entry.get())
if value <= 0:
raise ValueError
global disk_space_threshold_mb
disk_space_threshold_mb = value
messagebox.showinfo("Threshold Set", f"Auto-pause threshold set to {value} MB.")
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid positive integer for the disk space threshold.")
Corrected set_disk_threshold Function:
def set_disk_threshold():
"""Set the disk space threshold for auto-pausing."""
global disk_space_threshold_mb # Move global declaration to the top
try:
value = int(disk_threshold_entry.get())
if value <= 0:
raise ValueError
disk_space_threshold_mb = value
messagebox.showinfo("Threshold Set", f"Auto-pause threshold set to {value} MB.")
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid positive integer for the disk space threshold.")
5. Full Corrected Code
For clarity, here's the complete corrected version of your script with all necessary global declarations moved to the top of their respective functions:
import ttkbootstrap as tb
from ttkbootstrap.constants import *
from tkinter import filedialog, messagebox
import os
import threading
import psutil
import sys
# Initialize the main window
root = tb.Window(themename="cosmo") # You can choose any ttkbootstrap theme you like
root.title("DeepAscension Video2Image+")
root.geometry("800x600") # Set the desired window size
# Define any global variables you might be using
input_folders = []
input_videos = []
output_folder = ""
disk_space_threshold_mb = 500 # Example default value
DISK_CHECK_INTERVAL = 5000 # in milliseconds
stop_all_event = threading.Event()
errors = []
is_paused = False
output_folder_var = tb.StringVar()
# Define your UI components here
frame = tb.Frame(root)
frame.pack(fill=BOTH, expand=True)
from ttkbootstrap import Treeview
tree = Treeview(frame, columns=("Path", "Type", "Status"), show='headings')
tree.heading("Path", text="Path")
tree.heading("Type", text="Type")
tree.heading("Status", text="Status")
tree.pack(fill=BOTH, expand=True, padx=10, pady=10)
# Example Progress Bar and Status Label
progress_bar = tb.Progressbar(root, mode='indeterminate')
progress_bar.pack(fill=X, padx=10, pady=5)
status_label = tb.Label(root, text="Ready")
status_label.pack(fill=X, padx=10, pady=5)
def on_closing():
"""Handle window closing to ensure all threads are properly terminated."""
if messagebox.askokcancel("Quit", "Do you want to quit?"):
stop_all_event.set()
root.destroy()
def select_input_folders():
"""Allow user to select multiple input folders."""
while True:
folder = filedialog.askdirectory(title="Select Input Folder (Cancel to finish)")
if folder:
if folder not in input_folders and folder not in input_videos:
input_folders.append(folder)
tree.insert('', 'end', iid=folder, values=(folder, "Folder", "Pending"))
else:
messagebox.showwarning("Duplicate Entry", f"The entry '{folder}' is already selected.")
else:
break
def select_input_videos():
"""Allow user to select multiple video files."""
files = filedialog.askopenfilenames(
title="Select Video Files",
filetypes=[("Video Files", "*.mp4 *.avi *.mov *.mkv *.flv *.wmv")]
)
for file in files:
if file not in input_videos and file not in input_folders:
input_videos.append(file)
tree.insert('', 'end', iid=file, values=(file, "Video File", "Pending"))
else:
messagebox.showwarning("Duplicate Entry", f"The file '{file}' is already selected.")
def select_output_folder():
"""Allow user to select an output folder and set the output_folder_var."""
global output_folder # Declare global before using
global output_label
folder = filedialog.askdirectory(title="Select Output Folder")
if folder:
output_folder_var.set(folder)
output_folder = folder # Now safe to modify after declaring global
# Update UI elements that display the output folder
if 'output_label' in globals():
output_label.config(text=f"Output Folder: {folder}")
else:
output_label = tb.Label(root, text=f"Output Folder: {folder}")
output_label.pack(pady=5)
def process_videos():
"""Main function to process videos and folders."""
if not input_folders and not input_videos:
messagebox.showerror("Error", "Please select at least one input folder or video file.")
set_buttons_state(NORMAL)
return
if not output_folder_var.get():
messagebox.showerror("Error", "Please select an output folder.")
set_buttons_state(NORMAL)
return
# Start processing in a separate thread to avoid blocking the UI
processing_thread = threading.Thread(target=run_processing)
processing_thread.start()
def run_processing():
"""Run the actual video processing."""
set_buttons_state(DISABLED)
progress_bar.start()
status_label.config(text="Processing...")
# Placeholder for processing logic
# Replace this with your actual processing code
try:
# Simulate processing with sleep
import time
for i in range(5):
if stop_all_event.is_set():
raise Exception("Processing stopped by user.")
time.sleep(1)
status_label.config(text=f"Processing... {int((i+1)/5*100)}%")
# Simulate completion
finalize_processing()
except Exception as e:
errors.append(str(e))
finalize_processing()
def set_disk_threshold():
"""Set the disk space threshold for auto-pausing."""
global disk_space_threshold_mb # Declare global before using
try:
value = int(disk_threshold_entry.get())
if value <= 0:
raise ValueError
disk_space_threshold_mb = value
messagebox.showinfo("Threshold Set", f"Auto-pause threshold set to {value} MB.")
except ValueError:
messagebox.showerror("Invalid Input", "Please enter a valid positive integer for the disk space threshold.")
def finalize_processing():
"""Finalize the processing by updating the UI and displaying any errors."""
set_buttons_state(NORMAL)
progress_bar.stop()
if errors:
error_message = "\n\n".join(errors)
messagebox.showerror("Processing Completed with Errors", error_message)
else:
messagebox.showinfo("Success", "All videos have been successfully processed.")
progress_bar['value'] = 0
status_label.config(text="Processing completed.")
def monitor_disk_space():
"""Monitor disk space and auto-pause if below threshold."""
if stop_all_event.is_set():
return
output_path = output_folder_var.get()
if not output_path:
# If output path is not set, skip checking
root.after(DISK_CHECK_INTERVAL, monitor_disk_space)
return
try:
usage = psutil.disk_usage(output_path)
total = usage.total
used = usage.used
free = usage.free
percent = usage.percent
# Debugging: Print disk usage details
# print(f"Disk Usage for '{output_path}': Total={total}, Used={used}, Free={free}, Percent={percent}")
if free < disk_space_threshold_mb * 1024 * 1024:
global is_paused
if not is_paused:
on_pause()
is_paused = True
messagebox.showwarning("Auto-Pause", "Disk space below threshold. Processing has been paused.")
except Exception as e:
messagebox.showerror("Disk Space Error", f"Unable to determine disk space for '{output_path}'.\nError: {e}")
if not stop_all_event.is_set():
root.after(DISK_CHECK_INTERVAL, monitor_disk_space)
def on_pause():
"""Handle pause action."""
global is_paused
# Implement your pause functionality here
is_paused = True
# Example: Update status
status_label.config(text="Processing paused due to low disk space.")
def on_resume():
"""Handle resume action."""
global is_paused
# Implement your resume functionality here
is_paused = False
# Example: Update status
status_label.config(text="Processing resumed.")
# Restart disk monitoring if paused
monitor_disk_space()
def set_buttons_state(state):
"""Enable or disable buttons during processing."""
for widget in frame.winfo_children():
if isinstance(widget, tb.Button):
widget.config(state=state)
# Also control other buttons if necessary
# Register the on_closing function to handle window close event
root.protocol("WM_DELETE_WINDOW", on_closing)
# Optionally, start monitoring disk space after the main loop starts
root.after(1000, monitor_disk_space) # Start after 1 second
# Add UI Components for selecting input folders, videos, output folder, and setting disk threshold
controls_frame = tb.Frame(root)
controls_frame.pack(pady=10)
select_folders_button = tb.Button(controls_frame, text="Select Input Folders", command=select_input_folders)
select_folders_button.grid(row=0, column=0, padx=5)
select_videos_button = tb.Button(controls_frame, text="Select Input Videos", command=select_input_videos)
select_videos_button.grid(row=0, column=1, padx=5)
output_button = tb.Button(controls_frame, text="Select Output Folder", command=select_output_folder)
output_button.grid(row=0, column=2, padx=5)
process_button = tb.Button(root, text="Process", command=process_videos)
process_button.pack(pady=10)
disk_threshold_label = tb.Label(root, text="Disk Space Threshold (MB):")
disk_threshold_label.pack(pady=5)
disk_threshold_entry = tb.Entry(root, textvariable=tb.StringVar(value=str(disk_space_threshold_mb)))
disk_threshold_entry.pack(pady=5)
set_threshold_button = tb.Button(root, text="Set Threshold", command=set_disk_threshold)
set_threshold_button.pack(pady=10)
# Run the GUI loop
root.mainloop()
Key Takeaways
-
Always Declare global First: When modifying global variables inside a function, declare them as global before any other operations in that function.
-
Minimize Global Variables: Where possible, use StringVar, IntVar, and other Tkinter variables to manage state instead of separate global variables. This reduces complexity and potential conflicts.
-
Consistency in Variable Management: Ensure that all parts of your code consistently manage and reference the same variables to avoid bugs and unexpected behavior.
By applying these corrections, your application should handle the output path correctly without encountering the "path is used prior to global declaration" error.