TkinterDnD2 - Drag and Drop for Tkinter

0.4.3 · active · verified Fri Apr 17

TkinterDnD2 is a Python wrapper for George Petasis' tkDnD Tk extension version 2, enabling robust drag-and-drop functionality in Tkinter applications. It provides interfaces for registering widgets as drop targets and handling dropped data, including files, text, and custom types. The library is currently at version 0.4.3 and sees sporadic but active maintenance, focusing on cross-platform compatibility and stability for Tkinter projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a basic Tkinter window with a label that acts as a drag-and-drop target. It accepts file drops and prints the paths to the console, updating the label with the first dropped item's path.

import tkinter as tk
from tkinterdnd2 import DND_FILES, TkinterDnD

class MyDNDApp(TkinterDnD.Tk):
    def __init__(self):
        super().__init__()
        self.title("TkinterDnD2 Drop Example")
        self.geometry("400x300")

        self.dnd_label = tk.Label(
            self,
            text="Drag & drop files here!",
            width=40, height=10,
            relief="groove",
            bg="lightgray"
        )
        self.dnd_label.pack(padx=20, pady=20)

        # Register the label as a drop target for files
        self.dnd_label.drop_target_register(DND_FILES)
        # Bind the drop event to a handler function
        self.dnd_label.dnd_bind('<<Drop>>', self.handle_drop)

    def handle_drop(self, event):
        # event.data contains the dropped data (e.g., file paths)
        # It's a space-separated string if multiple files are dropped
        dropped_items = event.data.strip().split(' ') # Basic parsing
        self.dnd_label.config(text=f"Dropped: {dropped_items[0]}\n({len(dropped_items)} items)")
        print(f"Dropped items: {dropped_items}")

if __name__ == "__main__":
    app = MyDNDApp()
    app.mainloop()

view raw JSON →