0

I'm trying to make a tkinterdnd function that when called on can allow the user to drag and drop a file into the box, and when the box is closed it returns the file path for the file put in as event_data.

How do I get it to return this value if it is in the box?

def get_file_gui():
    def show_text(event):
        textarea.delete("1.0","end")
        textarea.insert("end",f"{event.data}\n")
        return event.data

    root=TkinterDnD.Tk()
    root.title("EFT Secure File Transfer")
    root.geometry('400x300')

    frame=Frame(root)
    frame.pack()

    textarea=Text(frame, height=30, width=40)
    textarea.pack(side=LEFT)
    textarea.drop_target_register(DND_FILES)
    textarea.dnd_bind('<<BIND>>', show_text)

    root.mainloop()
    return event_data
Agent859
  • 5
  • 3
  • You can't return values from bound functions. You will have to save it to a global variable or as an attribute of an object. – Bryan Oakley Aug 01 '23 at 17:57

2 Answers2

0

Here’s some example code to get you started that shows how to drag a file onto a tkinter widget (a text area) and get its path:

import TkinterDnD2 as tkdnd

def get_file_gui():
    def show_text(event):
        textarea.delete("1.0","end")
        textarea.insert("end",f"{event.data}\n")
        return event.data

    root=tkdnd.Tk()
    root.title("EFT Secure File Transfer")
    root.geometry('400x300')

    frame=tkdnd.Frame(root)
    frame.pack()

    textarea=tkdnd.Text(frame, height=30, width=40)
    textarea.pack(side=tkdnd.LEFT)
    textarea.drop_target_register(tkdnd.DND_FILES)
    textarea.dnd_bind('<<DROP>>', show_text)

    root.mainloop()

This code creates a window with a text area that can accept files that are dragged and dropped onto it. When a file is dropped onto the text area, the show_text function is called with an event object that contains the file path. The function then displays the file path in the text area by calling event.data.

Ben the Coder
  • 539
  • 2
  • 5
  • 21
0

You can create a local variable event_data inside get_file_gui() and update it inside nested function show_text():

def get_file_gui():
    event_data = None  # create and initialize "event_data"

    def show_text(event):
        nonlocal event_data
        event_data = event.data  # update "event_data"
        textarea.delete("1.0", "end")
        textarea.insert("end", f"{event.data}\n")

    root = TkinterDnD.Tk()
    root.title("EFT Secure File Transfer")
    root.geometry('400x300')

    frame = Frame(root)
    frame.pack()

    textarea = Text(frame, height=30, width=40)
    textarea.pack(side=LEFT)
    textarea.drop_target_register(DND_FILES)
    textarea.dnd_bind('<<Drop>>', show_text) # bind "<<Drop>>" instead of "<<BIND>>"

    root.mainloop()
    return event_data
acw1668
  • 40,144
  • 5
  • 22
  • 34