|
| 1 | +""" |
| 2 | +Drag-and-drop utility for file selection widgets. |
| 3 | +
|
| 4 | +Provides a reusable function to enable drag-and-drop file selection on tkinter widgets, |
| 5 | +specifically for Windows Explorer file drag-and-drop support. |
| 6 | +""" |
| 7 | + |
| 8 | +import os |
| 9 | +from typing import Callable, Optional |
| 10 | + |
| 11 | +try: |
| 12 | + from tkinterdnd2 import DND_FILES, TkinterDnD |
| 13 | + _HAS_DND = True |
| 14 | +except ImportError: |
| 15 | + _HAS_DND = False |
| 16 | + |
| 17 | + |
| 18 | +def enable_file_drop(widget, callback: Callable[[str], None], |
| 19 | + file_types: Optional[list[str]] = None) -> bool: |
| 20 | + """ |
| 21 | + Enable drag-and-drop file selection on a tkinter widget. |
| 22 | + |
| 23 | + Args: |
| 24 | + widget: The tkinter widget to enable drag-and-drop on |
| 25 | + callback: Function to call with the file path when a file is dropped |
| 26 | + file_types: Optional list of allowed file extensions (e.g., ['.csv', '.xlsx']) |
| 27 | + If None, all file types are allowed |
| 28 | + |
| 29 | + Returns: |
| 30 | + True if drag-and-drop was successfully enabled, False otherwise |
| 31 | + |
| 32 | + Example: |
| 33 | + >>> import tkinter as tk |
| 34 | + >>> entry = tk.Entry(root) |
| 35 | + >>> enable_file_drop(entry, lambda path: entry_var.set(path)) |
| 36 | + """ |
| 37 | + if not _HAS_DND: |
| 38 | + return False |
| 39 | + |
| 40 | + def _on_drop(event): |
| 41 | + """Handle the drop event.""" |
| 42 | + # The event.data can be a list of files or a single file path |
| 43 | + # It comes in a format like: {path1} {path2} or just path |
| 44 | + # We need to parse it correctly |
| 45 | + files = event.data |
| 46 | + |
| 47 | + # Handle different formats |
| 48 | + if isinstance(files, (list, tuple)): |
| 49 | + # Already a list |
| 50 | + file_list = files |
| 51 | + else: |
| 52 | + # Parse the string - files can be separated by spaces or in curly braces |
| 53 | + file_list = [] |
| 54 | + if files.startswith('{'): |
| 55 | + # Format: {path1} {path2} |
| 56 | + import re |
| 57 | + file_list = re.findall(r'\{([^}]+)\}', files) |
| 58 | + else: |
| 59 | + # Simple space-separated or single file |
| 60 | + # But be careful with paths containing spaces |
| 61 | + if os.path.exists(files.strip()): |
| 62 | + file_list = [files.strip()] |
| 63 | + else: |
| 64 | + # Try to split, but this might not work with spaces in paths |
| 65 | + file_list = [f.strip() for f in files.split() if f.strip()] |
| 66 | + |
| 67 | + # Get the first valid file |
| 68 | + for file_path in file_list: |
| 69 | + file_path = file_path.strip().strip('{}') |
| 70 | + |
| 71 | + # Validate file exists |
| 72 | + if not os.path.exists(file_path): |
| 73 | + continue |
| 74 | + |
| 75 | + # Validate file type if specified |
| 76 | + if file_types: |
| 77 | + ext = os.path.splitext(file_path)[1].lower() |
| 78 | + if ext not in file_types: |
| 79 | + continue |
| 80 | + |
| 81 | + # Call the callback with the first valid file |
| 82 | + callback(file_path) |
| 83 | + break |
| 84 | + |
| 85 | + try: |
| 86 | + # Register the widget for file drop |
| 87 | + widget.drop_target_register(DND_FILES) |
| 88 | + widget.dnd_bind('<<Drop>>', _on_drop) |
| 89 | + return True |
| 90 | + except Exception: |
| 91 | + return False |
| 92 | + |
| 93 | + |
| 94 | +def make_window_dnd_compatible(window): |
| 95 | + """ |
| 96 | + Make a tkinter window compatible with drag-and-drop. |
| 97 | + |
| 98 | + This should be called on the root window or Toplevel to enable DnD support. |
| 99 | + For regular tk.Tk() or tk.Toplevel(), this will upgrade them to support DnD. |
| 100 | + |
| 101 | + Args: |
| 102 | + window: A tk.Tk() or tk.Toplevel() window |
| 103 | + |
| 104 | + Returns: |
| 105 | + The window (potentially upgraded to TkinterDnD version) |
| 106 | + |
| 107 | + Note: |
| 108 | + If using TkinterDnD, you should create your root window as TkinterDnD.Tk() |
| 109 | + instead of tk.Tk() for best results. This function is a helper for existing windows. |
| 110 | + """ |
| 111 | + if not _HAS_DND: |
| 112 | + return window |
| 113 | + |
| 114 | + # If the window is already DnD-compatible, return it as-is |
| 115 | + if hasattr(window, 'drop_target_register'): |
| 116 | + return window |
| 117 | + |
| 118 | + # Otherwise, we can't upgrade an existing window easily |
| 119 | + # Just return the original window |
| 120 | + return window |
0 commit comments