#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2025/11/02 14:08:27 +0900> """ Drag and drop file to Listbox from Windows explorer. use tkinterdnd2. pip install tkinterdnd2 * Windows11 x64 25H2 + Python 3.10.10 64bit + tkinterdnd2 0.4.3 """ import tkinter as tk from tkinterdnd2 import * # from tkinterdnd2 import DND_FILES, TkinterDnD def all_clear(): """Listbox all clear""" listbox.delete(0, tk.END) def get_list_from_listbox(): """Get list from Listbox""" flist = list(listbox.get(0, tk.END)) return flist def drop(event): """Drop and drop to filer""" if listbox.get(0) == "Please file drop": listbox.delete(0, tk.END) lst = list(root.tk.splitlist(event.data)) # lst.sort() for s in lst: listbox.insert(tk.END, s) for s in get_list_from_listbox(): print(f"[{s}]") # Main window root = TkinterDnD.Tk() root.title("Drag and drop to Listbox") # root.geometry("640x200") LISTBOX_LIST_INIT = [ "Please file drop", "test 1 hoge fuga piyo", "test 2", "test 3", "test 4", "test 5", "test 6 Ut incididunt non amet elit reprehenderit elit cillum eu nostrud velit.", "test 7", "test 8", "test 9", ] frm = tk.Frame(root, relief=tk.GROOVE, bd=4) listbox = tk.Listbox( frm, width=40, height=5, font=("Meiryo UI", 14), justify="left", selectmode=tk.EXTENDED, ) for s in LISTBOX_LIST_INIT: listbox.insert(tk.END, s) # scrollbar scrlbary = tk.Scrollbar(frm, orient=tk.VERTICAL, command=listbox.yview) scrlbarx = tk.Scrollbar(frm, orient=tk.HORIZONTAL, command=listbox.xview) listbox.configure(yscrollcommand=scrlbary.set) listbox.configure(xscrollcommand=scrlbarx.set) btn = tk.Button(root, text="List Clear", command=all_clear) # layout frm.pack(fill=tk.BOTH, expand=True, padx=12, pady=12) listbox.grid(row=0, column=0, sticky=tk.NSEW) scrlbary.grid(row=0, column=1, sticky=tk.NS) scrlbarx.grid(row=1, column=0, sticky=tk.EW) frm.grid_columnconfigure(0, weight=1) frm.grid_rowconfigure(0, weight=1) btn.pack(padx=8, pady=8) # drag and drop bind listbox.drop_target_register(DND_FILES) listbox.dnd_bind("<>", drop) root.mainloop()