### Run Basic File Drop Example Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/quick-start.md Execute the Python script to start the file drop demo. Drag files from your file manager onto the listbox. ```bash python script.py # Now drag files from your file manager onto the listbox ``` -------------------------------- ### Bidirectional Drag & Drop Example Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Demonstrates setting up widgets for both dragging and dropping. ```Python import tkinter as tk from tkinterdnd2 import DND_FILES, TkinterDnD root = TkinterDnD.Tk() def drop_handler(event): files = root.tk.splitlist(event.data) print(f'Dropped: {files}') def drag_init(event): print('Drag initiated') widget1 = tk.Label(root, text='Widget 1 (Drag & Drop)', relief='raised', borderwidth=2) widget1.pack(padx=20, pady=10, fill='x') widget1.drop_target_register(DND_FILES) widget1.dnd_bind('<>', drop_handler) widget1.drag_source_register(DND_FILES) widget1.dnd_bind('<>', drag_init) widget2 = tk.Label(root, text='Widget 2 (Drag & Drop)', relief='raised', borderwidth=2) widget2.pack(padx=20, pady=10, fill='x') widget2.drop_target_register(DND_FILES) widget2.dnd_bind('<>', drop_handler) widget2.drag_source_register(DND_FILES) widget2.dnd_bind('<>', drag_init) root.mainloop() ``` -------------------------------- ### Drag Source Example Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Shows how to configure a widget as a drag source for TkinterDnD2. ```Python import tkinter as tk from tkinterdnd2 import DND_FILES, TkinterDnD root = TkinterDnD.Tk() def drag_start(event): # You can specify data and types here if needed # For files, TkinterDnD handles it automatically print('Drag started') label = tk.Label(root, text='Drag me') label.pack(padx=20, pady=20) # Register as a drag source for files label.drag_source_register(DND_FILES) label.dnd_bind('<>', drag_start) root.mainloop() ``` -------------------------------- ### Basic File Drops Example Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Demonstrates how to handle basic file drops using TkinterDnD2. ```Python import tkinter as tk from tkinterdnd2 import DND_FILES, TkinterDnD root = TkinterDnD.Tk() def drop_enter(event): widget = event.widget widget.config(bg='lightblue') print(f'Entering drop target: {event.data}') def drop_leave(event): widget = event.widget widget.config(bg='white') print(f'Leaving drop target: {event.data}') def drop(event): widget = event.widget widget.config(bg='white') files = root.tk.splitlist(event.data) print(f'Dropped files: {files}') label = tk.Label(root, text='Drag and drop files here') label.pack(padx=20, pady=20) label.drop_target_register(DND_FILES) label.dnd_bind('<>', drop_enter) label.dnd_bind('<>', drop_leave) label.dnd_bind('<>', drop) root.mainloop() ``` -------------------------------- ### Minimal tkinterdnd2 Example Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/README.md This is a basic example demonstrating how to set up a Tkinter window with a listbox that can accept dropped files. It registers the listbox as a drop target for files and binds a callback to handle the drop event. ```python from tkinterdnd2 import Tk, DND_FILES, COPY root = Tk() # Use this instead of tk.Tk() listbox = __import__('tkinter').Listbox(root) listbox.drop_target_register(DND_FILES) listbox.dnd_bind('<>', lambda e: listbox.insert(__import__('tkinter').END, e.data)) listbox.pack() root.mainloop() ``` -------------------------------- ### Install tkinterdnd2 Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/quick-start.md Install the library using pip. Requires Python 3.6+. ```bash pip install tkinterdnd2 ``` -------------------------------- ### Visual Feedback Example Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Demonstrates providing visual feedback to the user during drag and drop operations. ```Python import tkinter as tk from tkinterdnd2 import DND_FILES, TkinterDnD root = TkinterDnD.Tk() def drop_enter(event): widget = event.widget widget.config(bg='lightgreen') # Visual feedback on enter print(f'Entering drop target: {event.data}') def drop_leave(event): widget = event.widget widget.config(bg='white') # Revert background on leave print(f'Leaving drop target: {event.data}') def drop(event): widget = event.widget widget.config(bg='white') files = root.tk.splitlist(event.data) print(f'Dropped files: {files}') label = tk.Label(root, text='Drag and drop files here') label.pack(padx=20, pady=20) label.drop_target_register(DND_FILES) label.dnd_bind('<>', drop_enter) label.dnd_bind('<>', drop_leave) label.dnd_bind('<>', drop) root.mainloop() ``` -------------------------------- ### TkinterDnD2 Framework Integration Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Shows the basic setup for using TkinterDnD2 by creating a TkinterDnD.Tk instance. ```Python from tkinterdnd2 import TkinterDnD # Create a TkinterDnD root window root = TkinterDnD.Tk() # Your Tkinter application code here... root.mainloop() ``` -------------------------------- ### Error Handling Example Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Demonstrates basic error handling during drag and drop operations. ```Python import tkinter as tk from tkinterdnd2 import DND_FILES, TkinterDnD root = TkinterDnD.Tk() def drop_error(event): try: files = root.tk.splitlist(event.data) print(f'Dropped files: {files}') except Exception as e: print(f'Error processing drop: {e}') label = tk.Label(root, text='Drag files here (expect errors if invalid)') label.pack(padx=20, pady=20) label.drop_target_register(DND_FILES) label.dnd_bind('<>', drop_error) root.mainloop() ``` -------------------------------- ### Basic File Drop Example with Tkinter Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/module-tkinterdnd2.md Shows how to create a Tkinter window with a Listbox that accepts dropped files. The dropped file paths are appended to the listbox. ```python from tkinterdnd2 import Tk, DND_FILES root = Tk() root.title("File Drop Demo") listbox = tk.Listbox(root) listbox.insert(1, "drag files to here") listbox.drop_target_register(DND_FILES) listbox.dnd_bind('<>', lambda e: listbox.insert(tk.END, e.data)) listbox.pack() root.mainloop() ``` -------------------------------- ### Text Transfers Example Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Illustrates how to perform text data transfers with TkinterDnD2. ```Python import tkinter as tk from tkinterdnd2 import DND_TEXT, TkinterDnD root = TkinterDnD.Tk() def drop_text(event): text_data = event.data print(f'Dropped text: {text_data}') text_widget = tk.Text(root) text_widget.pack(padx=20, pady=20) text_widget.drop_target_register(DND_TEXT) text_widget.dnd_bind('<>', drop_text) root.mainloop() ``` -------------------------------- ### Example DragInitCmd Return Values Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/types.md Illustrates how to return different combinations of actions, types, and data from a drag initialization function. Supports single or multiple specifications. ```python def drag_init(event): # All data types with single action and type return (COPY, DND_TEXT, "Simple text") # Multiple possible actions and types return ((COPY, MOVE), (DND_TEXT, DND_FILES), ("text", "/path/to/file")) ``` -------------------------------- ### Advanced Patterns Example Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Illustrates advanced usage patterns for TkinterDnD2, such as custom data types. ```Python import tkinter as tk from tkinterdnd2 import TkinterDnD root = TkinterDnD.Tk() # Define a custom data type CUSTOM_TYPE = 'application/x-my-custom-data' def drop_custom(event): data = event.data print(f'Received custom data: {data}') def drag_custom(event): # Prepare custom data to be dragged custom_data = 'some_value' # TkinterDnD might require specific ways to set custom data # This is a conceptual example; actual implementation may vary print(f'Dragging custom data: {custom_data}') # Example: event.widget.dnd_start(custom_data, CUSTOM_TYPE) label_target = tk.Label(root, text='Drop custom data here') label_target.pack(padx=20, pady=10) label_target.drop_target_register(CUSTOM_TYPE) label_target.dnd_bind('<>', drop_custom) label_source = tk.Label(root, text='Drag custom data from here') label_source.pack(padx=20, pady=10) label_source.drag_source_register(CUSTOM_TYPE) label_source.dnd_bind('<>', drag_custom) root.mainloop() ``` -------------------------------- ### Unable to Load Binary Error Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/configuration.md This example shows the `RuntimeError` that is raised when Tkinterdnd2 is unable to load the required tkdnd library binary for the current platform. ```python RuntimeError: Unable to load tkdnd library. ``` -------------------------------- ### Platform Not Supported Error Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/configuration.md This example shows the `RuntimeError` that is raised when the detected platform is not supported by Tkinterdnd2. ```python RuntimeError: Platform not supported. ``` -------------------------------- ### Temporary Directory Configuration Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/MANIFEST.md Methods for getting and setting the temporary directory used for dropped files. ```APIDOC ## Temporary Directory Configuration ### Description Manages the temporary directory used for handling dropped files during drag and drop operations. ### Methods - **get_dropfile_tempdir()**: Retrieves the current temporary directory path. - **set_dropfile_tempdir(path)**: Sets the temporary directory path. ``` -------------------------------- ### Add Drag-and-Drop to PySimpleGUI Input Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/quick-start.md Integrates TkinterDnD2 with PySimpleGUI to enable file dropping into an Input element. Requires PySimpleGUI to be installed. ```python import PySimpleGUI as sg from tkinterdnd2 import TkinterDnD, DND_FILES, COPY sg.theme('DarkBlue3') layout = [ [sg.Text("Drag files here:")], [sg.Input(size=(40, 1), key="-FILE-")], [sg.Button("OK"), sg.Button("Cancel")], ] window = sg.Window("File Drop", layout, finalize=True) # Enable DnD TkinterDnD.require(window.TKroot) # Register input widget input_widget = window["-FILE-"].widget input_widget.drop_target_register(DND_FILES) def on_drop(event): path = event.data.strip() window["-FILE-"].update(path) return COPY input_widget.dnd_bind("<>", on_drop) while True: event, values = window.read() if event in (sg.WIN_CLOSED, "Cancel"): break window.close() ``` -------------------------------- ### Provide Visual Feedback for Drag Over Events Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/quick-start.md This example shows how to provide visual feedback to the user when dragging items over a Tkinter Listbox widget. It changes the background color of the widget when the drag enters and leaves, and inserts dropped files into the listbox. ```python import tkinter as tk from tkinterdnd2 import Tk, DND_FILES, COPY root = Tk() listbox = tk.Listbox(root, height=10) listbox.pack(padx=10, pady=10) listbox.drop_target_register(DND_FILES) def on_enter(event): # Highlight when cursor enters listbox.config(bg='lightgreen') return event.action def on_leave(event): # Remove highlight when cursor leaves listbox.config(bg='white') return event.action def on_drop(event): listbox.config(bg='white') files = listbox.tk.splitlist(event.data) for f in files: listbox.insert(tk.END, f) return COPY listbox.dnd_bind("<>", on_enter) listbox.dnd_bind("<>", on_leave) listbox.dnd_bind("<>", on_drop) root.mainloop() ``` -------------------------------- ### Registering a widget as a drag source with left mouse button and text type Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/class-DnDWrapper.md This example demonstrates how to register a Tkinter Label widget as a drag source. It specifies that the drag operation should be initiated by the left mouse button (1) and that the data being dragged is text (DND_TEXT). A callback function `drag_init` is also bound to handle the drag initialization command, returning the operation type (COPY), data type (DND_TEXT), and the actual data. ```Python from tkinterdnd2 import Tk, DND_TEXT, DND_FILES, COPY import tkinter as tk root = Tk() label = tk.Label(root, text="Drag this text") def drag_init(event): return (COPY, DND_TEXT, "Draggable text data") # Register left mouse button as drag source label.drag_source_register(1, DND_TEXT) label.dnd_bind("<>", drag_init) root.mainloop() ``` -------------------------------- ### Configuration Details Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/MANIFEST.md Documentation on Tk() constructor parameters, environment variables, platform detection, temporary file configuration, and PyInstaller integration. ```APIDOC ## Configuration Details ### Description Provides comprehensive documentation on various configuration aspects of the tkinterdnd2 library. ### Configuration Areas - **Tk() constructor parameters documented** - **All environment variables documented** - **Platform detection logic documented** - **Temporary file configuration documented** - **PyInstaller integration documented** ``` -------------------------------- ### Project Documentation Structure Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/README.md Illustrates the directory structure for the project's documentation files. ```markdown Documentation/ ├── README.md (this file) ├── API-OVERVIEW.md ├── quick-start.md ├── types.md ├── configuration.md └── api-reference/ ├── module-tkinterdnd2.md ├── class-DnDWrapper.md └── class-DnDEvent.md ``` -------------------------------- ### Framework Integration (PySimpleGUI) Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Illustrates integrating TkinterDnD2 with PySimpleGUI. ```Python import PySimpleGUI as sg from tkinterdnd2 import DND_FILES, TkinterDnD sg.theme('LightBlue3') layout = [[sg.Text('Drag and drop files here')], [sg.Output(size=(60, 10))]] window = sg.Window('PySimpleGUI DnD Example', layout, finalize=True) # Get the underlying Tkinter root window tk_root = window.TKroot # Wrap the Tkinter root window with TkinterDnD dnd_root = TkinterDnD.Tk(tk_root) def drop(event): files = dnd_root.tk.splitlist(event.data) print(f'Dropped files: {files}') # Find the Text element's underlying Tkinter widget (this might need adjustment based on PySimpleGUI version/element) # For simplicity, let's assume we can attach to the main window or a specific element if it exposes its Tk widget # This part is highly dependent on how PySimpleGUI exposes its widgets. # A common approach is to find the specific element's widget. # Example: If you had a sg.Image or sg.Text that you wanted to be a drop target # You would need to get its tk widget. This is often not directly exposed. # For a general window drop, you might attach to the root. dnd_root.dnd_bind('<>', drop) while True: event, values = window.read() if event == sg.WIN_CLOSED: break window.close() ``` -------------------------------- ### Basic File Drop and Open Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/quick-start.md Demonstrates how to create a Tkinter listbox that accepts dropped files from the OS file manager. Double-clicking an item opens it with the default application. ```python import tkinter as tk from tkinterdnd2 import Tk, DND_FILES, COPY import os import subprocess root = Tk() root.title("File Browser") root.geometry("500x400") listbox = tk.Listbox(root) listbox.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) listbox.drop_target_register(DND_FILES) def on_drop(event): files = listbox.tk.splitlist(event.data) for file in files: listbox.insert(tk.END, file) return COPY def on_double_click(event): selection = listbox.curselection() if selection: file = listbox.get(selection[0]) try: if os.name == 'nt': os.startfile(file) else: subprocess.Popen(['xdg-open', file]) except Exception as e: print(f"Cannot open: {e}") listbox.dnd_bind("<>", on_drop) listbox.bind("", on_double_click) root.mainloop() ``` -------------------------------- ### Add Drag-and-Drop to CustomTkinter Entry Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/quick-start.md Integrates TkinterDnD2 with CustomTkinter to enable file dropping into a CTkEntry widget. Requires the CustomTkinter library to be installed. ```python import customtkinter as ctk from tkinterdnd2 import TkinterDnD, DND_FILES, COPY app = ctk.CTk() app.title("CustomTkinter DnD") # Enable DnD on existing root TkinterDnD.require(app) entry = ctk.CTkEntry(app, placeholder_text="Drop a file here...") entry.pack(padx=20, pady=20) entry.drop_target_register(DND_FILES) def on_drop(event): path = event.data.strip() # Remove quotes/whitespace entry.delete(0, ctk.END) entry.insert(0, path) return COPY entry.dnd_bind("<>", on_drop) app.mainloop() ``` -------------------------------- ### Handling File Drops with Type Checking Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/class-DnDEvent.md Configure a widget to accept file drops and process the dropped file paths. The callback function prints common source types and inserts file paths into a listbox. ```python from tkinterdnd2 import Tk, DND_FILES, COPY root = Tk() listbox = tk.Listbox(root) listbox.drop_target_register(DND_FILES) def on_drop_files(event): print(f"Common types: {event.commonsourcetypes}") files = listbox.tk.splitlist(event.data) for filepath in files: listbox.insert(tk.END, filepath) return COPY listbox.dnd_bind("<>", on_drop_files) root.mainloop() ``` -------------------------------- ### Create a Drop Target Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/START-HERE.txt Register a widget as a drop target to accept file drops. Bind the '<>' event to a handler function that processes the dropped data. ```Python root = Tk() widget.drop_target_register(DND_FILES) widget.dnd_bind("<>", lambda e: handle_drop(e.data)) ``` -------------------------------- ### Get TkDND Temporary Directory Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/class-DnDWrapper.md Retrieves the path to the temporary directory used by tkdnd for storing dropped files. This directory can be influenced by environment variables. ```python tempdir = root.get_dropfile_tempdir() print(f"TkDND temp directory: {tempdir}") ``` -------------------------------- ### Framework Integration (CustomTkinter) Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Shows how to integrate TkinterDnD2 with the CustomTkinter library. ```Python import customtkinter from tkinterdnd2 import DND_FILES, TkinterDnD class App(TkinterDnD.CTk): def __init__(self): super().__init__() self.title("CustomTkinter DnD Example") def drop_enter(event): event.widget.configure(fg_color="#DDEEFF") def drop_leave(event): event.widget.configure(fg_color="#EFEFEF") def drop(event): files = self.tk.splitlist(event.data) print(f"Dropped files: {files}") event.widget.configure(fg_color="#EFEFEF") self.label = customtkinter.CTkLabel(self, text="Drag and drop files here") self.label.pack(padx=20, pady=20) self.label.drop_target_register(DND_FILES) self.label.dnd_bind('<>', drop_enter) self.label.dnd_bind('<>', drop_leave) self.label.dnd_bind('<>', drop) app = App() app.mainloop() ``` -------------------------------- ### Manage Temporary Directory for File Drops Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/configuration.md Get the current temporary directory used by tkdnd or set a custom one. This is useful for controlling where dropped files are temporarily stored. ```python from tkinterdnd2 import Tk import tempfile root = Tk() # Get current temp directory current_temp = root.get_dropfile_tempdir() print(f"Temp dir: {current_temp}") # Set a custom temp directory custom_temp = tempfile.mkdtemp(prefix='dnd_') root.set_dropfile_tempdir(custom_temp) ``` -------------------------------- ### Initialize TkinterDnD Tk Class Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/configuration.md Demonstrates initializing the TkinterDnD.Tk() class with standard Tkinter parameters. These parameters control the underlying Tk window but do not directly affect drag-and-drop functionality. ```python from tkinterdnd2 import Tk root = Tk( screenName=None, baseName=None, className='Tk', useTk=True, sync=False, use='', ) ``` -------------------------------- ### DragInitCmd Event Binding Source: https://github.com/eliav2/tkinterdnd2/blob/master/docs/tkDND.htm This event is triggered when a drag action is about to start. The binding script must return a list containing supported drop actions, format types, and the data to be dropped. ```Tcl bind .drag_source <> \ {list copy DND_Text {Hellow world!}} ``` -------------------------------- ### Module Structure Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/API-OVERVIEW.md Illustrates the directory structure of the tkinterdnd2 library, highlighting the main files and their purposes. ```text tkinterdnd2/ ├── __init__.py (exports constants and main Tk class) └── TkinterDnD.py (core DnD wrapper implementation) ``` -------------------------------- ### Handling Drop Enter/Leave Events Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/class-DnDEvent.md Implement callbacks for when a drag item enters or leaves a drop target widget. These functions can visually indicate the drop target state and return the desired action. ```python def on_drop_enter(event): print(f"Enter event from {event.widget}") print(f"Available types: {event.types}") event.widget.config(bg='lightblue') return event.action def on_drop_leave(event): print(f"Leave event from {event.widget}") event.widget.config(bg='white') return event.action widget.drop_target_register(DND_TEXT) widget.dnd_bind("<>", on_drop_enter) widget.dnd_bind("<>", on_drop_leave) ``` -------------------------------- ### Basic File Drop Target Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/quick-start.md Create a Tkinter window with a listbox that accepts dropped files. The listbox is registered as a drop target for files. ```python import tkinter as tk from tkinterdnd2 import Tk, DND_FILES, COPY root = Tk() # Use TkinterDnD.Tk instead of tk.Tk root.title("File Drop Demo") root.geometry("400x300") # Create a listbox to receive files listbox = tk.Listbox(root) listbox.pack(fill=tk.BOTH, expand=True, padx=10, pady=10) # Register as a drop target for files listbox.drop_target_register(DND_FILES) # Handle drop events def on_drop(event): files = listbox.tk.splitlist(event.data) for file in files: listbox.insert(tk.END, file) return COPY listbox.dnd_bind("<>", on_drop) root.mainloop() ``` -------------------------------- ### Event Sequences Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/API-OVERVIEW.md DnD events are bound using these sequence strings, each triggering specific actions and providing available properties. ```APIDOC ## Event Sequences ### Description DnD events are bound using these sequence strings, each triggering specific actions and providing available properties. ### Sequences - **<>** - Trigger: Cursor enters drop target - Available Properties: action, actions, types, modifiers, x_root, y_root, widget - **<>** - Trigger: Cursor moves over drop target - Available Properties: action, actions, types, modifiers, x_root, y_root, widget - **<>** - Trigger: Cursor leaves drop target - Available Properties: action, actions, widget - **<>** - Trigger: User releases to complete drop - Available Properties: All properties - **<>** - Trigger: Drop with specific type filter - Available Properties: All properties - **<>** - Trigger: Drag source initiates drag - Available Properties: button, modifiers, types, x_root, y_root, widget - **<>** - Trigger: Drag source ends drag - Available Properties: action, widget ``` -------------------------------- ### Registering a File Drop Target Source: https://github.com/eliav2/tkinterdnd2/blob/master/docs/tkDND.htm Adds the ability for a drop target to accept file drops by registering the 'DND_Files' type and defining a specialized drop binding. ```Tcl tkdnd::drop_target register .drop_target DND_Files bind .drop_target <> \ {puts %D; %W configure -bg white} ``` -------------------------------- ### Access TkinterDnD Core Components Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/module-tkinterdnd2.md Demonstrates how to import and access the main TkinterDnD window class and its version information. ```python from tkinterdnd2 import TkinterDnD # Access the Tk class root = TkinterDnD.Tk() # Access the version version = TkinterDnD.TkdndVersion ``` -------------------------------- ### Basic TkinterDnD2 Usage Source: https://github.com/eliav2/tkinterdnd2/blob/master/README.md Demonstrates how to set up a Tkinter window with a listbox that can accept dropped files. Use TkinterDnD.Tk() instead of tk.Tk() and register the widget as a drop target. ```python import tkinter as tk from tkinterdnd2 import DND_FILES, TkinterDnD root = TkinterDnD.Tk() # notice - use this instead of tk.Tk() lb = tk.Listbox(root) lb.insert(1, "drag files to here") # register the listbox as a drop target lb.drop_target_register(DND_FILES) lb.dnd_bind('<>', lambda e: lb.insert(tk.END, e.data)) lb.pack() root.mainloop() ``` -------------------------------- ### Configure PyInstaller for tkinterdnd2 Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/configuration.md Bundle tkdnd binaries with your application using PyInstaller. Copy the hook file and use the --additional-hooks-dir flag during the build process. ```bash pyinstaller -F -w myapp.py --additional-hooks-dir=. ``` -------------------------------- ### Drag Source with Type Information Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/class-DnDEvent.md Register a widget as a drag source for specific data types (e.g., text, files). The `<>` callback allows inspection of the target's supported types and returns the data to be dragged. ```python from tkinterdnd2 import Tk, DND_TEXT, DND_FILES, COPY, ASK root = Tk() label = tk.Label(root, text="Drag me") label.drag_source_register(DND_TEXT, DND_FILES) def on_drag_init(event): # Inspect what the target supports print(f"Target types: {event.types}") print(f"Modifiers: {event.modifiers}") data = "Text to drag" return ((COPY, ASK), DND_TEXT, data) label.dnd_bind("<>", on_drag_init) root.mainloop() ``` -------------------------------- ### Tk Class Constructor Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/module-tkinterdnd2.md Instantiate the enhanced Tkinter root window with drag-and-drop support. Pass positional and keyword arguments to the underlying tkinter.Tk constructor. ```python from tkinterdnd2 import Tk root = Tk() root.title("My Application") root.geometry("400x300") ``` -------------------------------- ### require Function Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/MANIFEST.md Enables drag and drop functionality on an existing Tkinter root window. ```APIDOC ## require(tkroot) Function ### Description Enables drag and drop functionality on an existing Tkinter root window. ### Parameters - **tkroot** (Tk) - The Tkinter root window instance to enable DnD on. ``` -------------------------------- ### Registering a Text Drop Target Source: https://github.com/eliav2/tkinterdnd2/blob/master/docs/tkDND.htm Registers a window as a drop target for text and defines bindings for drop events to provide visual feedback and handle dropped data. ```Tcl label .drop_target -text {Text Drop Target!} -bg white tkdnd::drop_target register .drop_target DND_Text bind .drop_target <> {%W configure -bg yellow; list copy} bind .drop_target <> {list copy} bind .drop_target <> {%W configure -bg white} bind .drop_target <> {%W configure -text %D; %W configure -bg white} ``` -------------------------------- ### Registering a Drag Source Source: https://github.com/eliav2/tkinterdnd2/blob/master/docs/tkDND.htm Registers a window as a drag source and defines the necessary binding for the 'DragInitCmd' event to specify drag actions, types, and data. ```Tcl tkdnd::drag_source register .text_drag_source bind .text_drag_source <> \ {list {copy move} DND_Text {Hello from Tk!}} ``` -------------------------------- ### Detect Operating System Platform Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/configuration.md Identify the current operating system to apply platform-specific logic. This snippet checks if the system is Windows and retrieves architecture information. ```python import os import platform system = platform.system() if system == "Windows": # Windows-specific code machine = os.environ.get('PROCESSOR_ARCHITECTURE', platform.machine()) else: machine = platform.machine() ``` -------------------------------- ### Create a Drag Source Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/START-HERE.txt Register a widget as a drag source to make its content draggable. Bind the '<>' event to a handler function that specifies the data and type to be dragged. ```Python widget.drag_source_register(1, DND_TEXT) widget.dnd_bind("<>", lambda e: (COPY, DND_TEXT, data)) ``` -------------------------------- ### Standard Import Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/API-OVERVIEW.md Imports specific components from the tkinterdnd2 library for direct use. ```python from tkinterdnd2 import Tk, DND_TEXT, DND_FILES, COPY, MOVE ``` -------------------------------- ### TkinterDnD2 require() function Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/COMPLETENESS-REPORT.txt Demonstrates the use of the require() function for framework integration. ```Python from tkinterdnd2 import TkinterDnD # Ensure TkinterDnD is initialized TkinterDnD.require() # Now you can use TkinterDnD features, e.g., TkinterDnD.Tk() root = TkinterDnD.Tk() # ... rest of your application root.mainloop() ``` -------------------------------- ### PySimpleGUI Integration with TkinterDnD2 Source: https://github.com/eliav2/tkinterdnd2/blob/master/README.md Shows how to integrate TkinterDnD2 with PySimpleGUI by using TkinterDnD.require() on the existing root. This allows widgets within PySimpleGUI to act as drop targets. ```python import PySimpleGUI as sg from tkinterdnd2 import TkinterDnD, DND_FILES def on_drop(event): window["-FILE-"].update(event.data) layout = [ [sg.Text("Drag & Drop a File Here")], [sg.Input("", key="-FILE-")], [sg.Button("OK"), sg.Button("Cancel")], ] window = sg.Window("File Drop", layout, finalize=True) # Inject DnD into PySimpleGUI's own root — no dummy window needed TkinterDnD.require(window.TKroot) # Register any widget as a drop target window["-FILE-"].widget.drop_target_register(DND_FILES) window["-FILE-"].widget.dnd_bind("<>", on_drop) while True: event, values = window.read() if event in (sg.WIN_CLOSED, "Cancel"): break window.close() ``` -------------------------------- ### TixTk Class Source: https://github.com/eliav2/tkinterdnd2/blob/master/docs/TkinterDnD2.rst Documentation for the TixTk class, a Tkinter-compatible class that supports drag and drop features. ```APIDOC ## TixTk Class A Tkinter-compatible class that integrates drag and drop capabilities. ### Members This class includes documented and undocumented members and shows its inheritance hierarchy. ``` -------------------------------- ### Type Name Aliases Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/types.md Lists and explains the type name aliases used within tkinterdnd2 and tkdnd documentation. ```APIDOC ## Type Name Aliases ### Description Provides a reference for type name aliases encountered in tkinterdnd2's source code and related tkdnd documentation. It maps these aliases to their corresponding data types or platform specifics. ### Aliases Table | Alias | Refers To | Platform | |------------------|-------------------|--------------| | `DND_Text` | Text data | Cross-platform | | `DND_Files` | File list | Cross-platform | | `CF_UNICODETEXT` | Windows Unicode | Windows | | `CF_TEXT` | Windows ANSI | Windows | | `CF_HDROP` | Windows file drop | Windows | | `text/plain` | Text (MIME) | Unix/X11 | | `text/uri-list` | File list (MIME) | Unix/X11 | ### Usage Note When using tkinterdnd2, it is recommended to prefer the library's constants (e.g., `DND_TEXT`, `DND_FILES`) over platform-specific or MIME type names for better portability and clarity. ``` -------------------------------- ### File Drop Integration with PySimpleGUI Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/module-tkinterdnd2.md Demonstrates how to integrate TkinterDnD's file drop functionality into a PySimpleGUI application. Requires TkinterDnD.require() to be called with the PySimpleGUI window's root Tk object. ```python from tkinterdnd2 import TkinterDnD, DND_FILES import PySimpleGUI as sg layout = [[sg.Input(key="-FILE-")]] window = sg.Window("File Drop", layout, finalize=True) TkinterDnD.require(window.TKroot) window["-FILE-"].widget.drop_target_register(DND_FILES) window["-FILE-"].widget.dnd_bind("<>", lambda e: window["-FILE-"].update(e.data)) ``` -------------------------------- ### Integrate tkinterdnd2 with CustomTkinter Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/START-HERE.txt This snippet shows how to import and initialize tkinterdnd2 when using a framework like CustomTkinter. Ensure TkinterDnD is required by the application instance. ```python from tkinterdnd2 import TkinterDnD app = CustomTkinter.CTk() # or PySimpleGUI or similar TkinterDnD.require(app) ``` -------------------------------- ### Handle Multiple Drop Types on a Single Widget Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/quick-start.md Demonstrates how a single Tkinter widget can handle multiple drop types (files and text) using type-specific bindings. This allows for more granular control over different data formats. ```python import tkinter as tk from tkinterdnd2 import Tk, DND_TEXT, DND_FILES, COPY root = Tk() # Single widget handles multiple types widget = tk.Frame(root) widget.pack(fill=tk.BOTH, expand=True) label = tk.Label(widget, text="Drop files or text here", fg='gray') label.pack(pady=50) widget.drop_target_register(DND_FILES, DND_TEXT) def on_file_drop(event): files = widget.tk.splitlist(event.data) label.config(text=f"Dropped {len(files)} files") return COPY def on_text_drop(event): label.config(text=f"Dropped text: {event.data[:50]}...") return COPY # Use type-specific binding widget.dnd_bind("<>", on_file_drop) widget.dnd_bind("<>", on_text_drop) root.mainloop() ``` -------------------------------- ### Handling Text Drops Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/class-DnDEvent.md Register a widget as a text drop target and define a callback function to process dropped text. The callback inserts the text at the drop location. ```python from tkinterdnd2 import Tk, DND_TEXT, COPY root = Tk() text_widget = tk.Text(root) text_widget.drop_target_register(DND_TEXT) def on_drop_text(event): print(f"Received text: {event.data}") print(f"At position: ({event.x_root}, {event.y_root})") # Insert at drop location index = text_widget.index(f"@{event.x_root - text_widget.winfo_rootx()},{event.y_root - text_widget.winfo_rooty()}") text_widget.insert(index, event.data) return COPY text_widget.dnd_bind("<>", on_drop_text) root.mainloop() ``` -------------------------------- ### tkdnd::SetDropFileTempDirectory Source: https://github.com/eliav2/tkinterdnd2/blob/master/docs/tkDND.htm Sets the temporary directory for storing dropped files. ```APIDOC ## tkdnd::SetDropFileTempDirectory ### Description Sets the temporary directory to be used for storing dropped files. This allows customization of where temporary files are placed. ### Command Signature `tkdnd::SetDropFileTempDirectory _directory_` ### Parameters * **_directory_** (string) - The path to the directory to be used as the temporary storage for dropped files. ``` -------------------------------- ### Constants Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/MANIFEST.md Provides constants for drag and drop actions and data types. ```APIDOC ## Constants ### Description Defines constants used for specifying actions and data types in drag and drop operations. ### Action Constants - **COPY**: Indicates a copy action. - **MOVE**: Indicates a move action. - **LINK**: Indicates a link action. - **ASK**: Indicates an ask action. - **PRIVATE**: Indicates a private action. - **REFUSE_DROP**: Indicates refusal to drop. - **NONE**: Indicates no specific action. ### Data Type Constants - **DND_TEXT**: Represents text data. - **DND_FILES**: Represents file data. - **DND_ALL**: Represents all data types. - **CF_UNICODETEXT**: Represents Unicode text data. - **CF_TEXT**: Represents plain text data. - **CF_HDROP**: Represents a handle to dropped files. - **FileGroupDescriptor**: Represents a file group descriptor. - **FileGroupDescriptorW**: Represents a wide character file group descriptor. ``` -------------------------------- ### Set Temporary Directory for Drag and Drop Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/configuration.md Configure a specific directory for temporary files used during drag-and-drop operations. This allows for periodic cleanup of old files. ```python import tempfile import os from tkinterdnd2 import Tk root = Tk() dnd_temp = tempfile.mkdtemp(prefix='app_dnd_') root.set_dropfile_tempdir(dnd_temp) # Later, periodically clean up old files for file in os.listdir(dnd_temp): if is_old(file): os.remove(os.path.join(dnd_temp, file)) ``` -------------------------------- ### Binding a Drag Initialization Handler Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/class-DnDWrapper.md Register a callback function to handle the '<>' event, which is triggered when a drag operation begins from a widget. The handler must return a tuple specifying the allowed actions, data types, and the data to be transferred. ```Python def drag_init(event): data = "This is draggable text" return (COPY, DND_TEXT, data) label.drag_source_register(DND_TEXT) label.dnd_bind("<>", drag_init) ``` -------------------------------- ### PyInstaller Integration Command Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/api-reference/module-tkinterdnd2.md Provides the command-line instruction for bundling a TkinterDnD2 application with PyInstaller, including the necessary hook file. ```bash pyinstaller -F -w myproject/myproject.py --additional-hooks-dir=. ``` -------------------------------- ### Tk Class Source: https://github.com/eliav2/tkinterdnd2/blob/master/docs/TkinterDnD2.rst Documentation for the Tk class, the main Tkinter root window enhanced with drag and drop functionality. ```APIDOC ## Tk Class The main Tkinter root window class, extended to support drag and drop operations. ### Members This class contains documented and undocumented members, and its inheritance is also shown. ``` -------------------------------- ### Asynchronous File Processing with Threads Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/quick-start.md Handles potentially long-running file processing in a background thread to keep the UI responsive. UI updates are scheduled back on the main thread using `root.after`. ```python import threading def on_drop(event): files = listbox.tk.splitlist(event.data) # Process in background thread thread = threading.Thread(target=process_files, args=(files,)) thread.daemon = True thread.start() return COPY def process_files(files): for file in files: result = expensive_operation(file) # Schedule UI update on main thread root.after(0, lambda f=file, r=result: update_ui(f, r)) ``` -------------------------------- ### Avoid Invalid Type Registration Source: https://github.com/eliav2/tkinterdnd2/blob/master/_autodocs/types.md Demonstrates incorrect ways to register drop target types. Using string literals like 'files' or 'DND_Files' instead of the exported constants can lead to unrecognized types and unexpected behavior. ```python widget.drop_target_register('files') # Not recognized widget.drop_target_register('DND_Files') # Use DND_FILES constant ```