import tkinter as tk from tkinter import filedialog, messagebox import os import json class FileHandler: """Handler for file operations.""" def __init__(self, root): """ Initialize the file handler. Args: root: The Tkinter root window. """ self.root = root def browse_file(self, title="Select File", filetypes=None): """Open a file dialog to select a file. Args: title (str): The title of the file dialog. filetypes (list): List of file type tuples (description, pattern). Returns: str: The selected file path, or None if no file was selected. """ if filetypes is None: filetypes = [("All files", "*.*")] file_path = filedialog.askopenfilename( title=title, filetypes=filetypes ) return file_path if file_path else None def save_file(self, title="Save File", filetypes=None, defaultextension="", initialfile=""): """Open a file dialog to save a file. Args: title (str): The title of the file dialog. filetypes (list): List of file type tuples (description, pattern). defaultextension (str): Default file extension. initialfile (str): The initial filename to suggest. Returns: str: The selected file path, or None if no file was selected. """ if filetypes is None: filetypes = [("All files", "*.*")] file_path = filedialog.asksaveasfilename( title=title, filetypes=filetypes, defaultextension=defaultextension, initialfile=initialfile ) return file_path if file_path else None def save_text_to_file(self, text, title="Save Text", filetypes=None, defaultextension=".txt"): """Save text to a file. Args: text (str): The text to save. title (str): The title of the file dialog. filetypes (list): List of file type tuples (description, pattern). defaultextension (str): Default file extension. Returns: bool: True if the file was saved successfully, False otherwise. """ file_path = self.save_file(title, filetypes, defaultextension) if file_path: try: with open(file_path, 'w') as f: f.write(text) return True except Exception as e: messagebox.showerror("Error", f"Failed to save file: {str(e)}") return False def save_json_to_file(self, data, title="Save JSON", filetypes=None, defaultextension=".json"): """Save JSON data to a file. Args: data: The JSON data to save. title (str): The title of the file dialog. filetypes (list): List of file type tuples (description, pattern). defaultextension (str): Default file extension. Returns: bool: True if the file was saved successfully, False otherwise. """ file_path = self.save_file(title, filetypes, defaultextension) if file_path: try: with open(file_path, 'w') as f: json.dump(data, f, indent=4) return True except Exception as e: messagebox.showerror("Error", f"Failed to save file: {str(e)}") return False def load_json_from_file(self, title="Load JSON", filetypes=None): """Load JSON data from a file. Args: title (str): The title of the file dialog. filetypes (list): List of file type tuples (description, pattern). Returns: dict: The loaded JSON data, or None if no file was selected or loading failed. """ if filetypes is None: filetypes = [("JSON files", "*.json"), ("All files", "*.*")] file_path = self.browse_file(title, filetypes) if file_path: try: with open(file_path, 'r') as f: return json.load(f) except Exception as e: messagebox.showerror("Error", f"Failed to load file: {str(e)}") return None # Example usage (for testing) if __name__ == '__main__': root = tk.Tk() root.title("File Handler Test") root.geometry("400x300") # Create file handler file_handler = FileHandler(root) # Test buttons def test_browse(): file_path = file_handler.browse_file( title="Select a file", filetypes=[("Text files", "*.txt"), ("All files", "*.*")] ) if file_path: print(f"Selected file: {file_path}") def test_save(): success = file_handler.save_text_to_file( "Test text content", title="Save text file", filetypes=[("Text files", "*.txt")] ) if success: print("File saved successfully") def test_json(): data = {"test": "data", "number": 123} success = file_handler.save_json_to_file( data, title="Save JSON file" ) if success: print("JSON file saved successfully") ttk.Button(root, text="Browse File", command=test_browse).pack(pady=5) ttk.Button(root, text="Save Text", command=test_save).pack(pady=5) ttk.Button(root, text="Save JSON", command=test_json).pack(pady=5) root.mainloop()