How to Install and Use TkDnD with Python Tkinter on OSX?

后端 未结 4 1194
情话喂你
情话喂你 2020-12-03 16:35

I\'ve spent some time to search for workable solution to do Drag and Drop behavior with Python Tkinter on OSX platform, and the most possible solution found is TkDnD library

4条回答
  •  再見小時候
    2020-12-03 17:05

    I got this working on both Windows (10) and OSX (10.11) by downloading:
    A) Tk extensions tkdnd2.8 from https://sourceforge.net/projects/tkdnd/
    B) Python wrapper TkinterDnD2 from https://sourceforge.net/projects/tkinterdnd/

    On OSX:
    1) Copy the tkdnd2.8 directory to /Library/Tcl
    2) Copy the TkinterDnD2 directory to /Library/Frameworks/Python.framework/Versions/.../lib/python/site-packages
    (Use the sudo command for copying files on OSX due to permissions.)

    On Windows:
    1) Copy the tkdnd2.8 directory to ...\Python\tcl
    2) Copy the TkinterDnD2 directory to ...\Python\Lib\site-packages

    And here's a simple test case based on python drag and drop explorer files to tkinter entry widget. The TkinterDnD2 download comes with much more robust examples.

        import sys
        if sys.version_info[0] == 2:
            from Tkinter import *
        else:
            from tkinter import *
        from TkinterDnD2 import *
    
        def drop(event):
            entry_sv.set(event.data)
    
        root = TkinterDnD.Tk()
        entry_sv = StringVar()
        entry_sv.set('Drop Here...')
        entry = Entry(root, textvar=entry_sv, width=80)
        entry.pack(fill=X, padx=10, pady=10)
        entry.drop_target_register(DND_FILES)
        entry.dnd_bind('<>', drop)
        root.mainloop()
    

    Update: the above procedure works for Python 2 or 3.

提交回复
热议问题