I have recently decided to start learning Python and while doing several small projects as a hands-on approach, i discovered the customtkinter
library (https://github.com/TomSchimansky/CustomTkinter) for more modern looking GUI development with Python.
I wanted to do something which either requires a drag-and-drop component for files or a file picker dialogue, which is seemingly somewhat present for the original tkinter
library with the tkinterdnd2
module, but it doesn't seem to be directly mentioned in the documentation for the customtkinter
library wrapper.
Does anyone know how to use drag-and-drop for files with customtkinter
specifically?
If there is no direct wrapper with customtkinter
, is there a way to apply the styles of customtkinter
to the tkinderdnd2
module? When using it like this, obviously it just uses the default tkinter
style:
from tkinter import TOP, Entry, Label, StringVar
from tkinterdnd2 import *
def get_path(event):
pathLabel.configure(text = event.data)
root = TkinterDnD.Tk()
root.geometry("350x100")
root.title("Get file path")
nameVar = StringVar()
entryWidget = Entry(root)
entryWidget.pack(side=TOP, padx=5, pady=5)
pathLabel = Label(root, text="Drag and drop file in the entry box")
pathLabel.pack(side=TOP)
entryWidget.drop_target_register(DND_ALL)
entryWidget.dnd_bind("<<Drop>>", get_path)
root.mainloop()
If you look into the source code of TkinterDnD
:
class Tk(tkinter.Tk, DnDWrapper):
'''Creates a new instance of a tkinter.Tk() window; all methods of the
DnDWrapper class apply to this window and all its descendants.'''
def __init__(self, *args, **kw):
tkinter.Tk.__init__(self, *args, **kw)
self.TkdndVersion = _require(self)
You can create another custom class using customtkinter.CTk
instead of tkinter.Tk
:
from tkinter import StringVar, TOP
from tkinterdnd2 import TkinterDnD, DND_ALL
import customtkinter as ctk
class Tk(ctk.CTk, TkinterDnD.DnDWrapper):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.TkdndVersion = TkinterDnD._require(self)
ctk.set_appearance_mode("dark")
#ctk.set_default_color_theme("blue")
def get_path(event):
pathLabel.configure(text = event.data)
#root = TkinterDnD.Tk()
root = Tk()
root.geometry("350x100")
root.title("Get file path")
nameVar = StringVar()
entryWidget = ctk.CTkEntry(root)
entryWidget.pack(side=TOP, padx=5, pady=5)
pathLabel = ctk.CTkLabel(root, text="Drag and drop file in the entry box")
pathLabel.pack(side=TOP)
entryWidget.drop_target_register(DND_ALL)
entryWidget.dnd_bind("<<Drop>>", get_path)
root.mainloop()
Result: