15

In Kivy, I am trying to build an interface where the user can drag and drop a file into a widget (text input) and then my code would retrieve the file system path of that file (/path/to/users.file). That seems like a simpler approach than using the FileChooser widget, but how would I do it?

Thanks!

fire_water
  • 1,380
  • 1
  • 19
  • 33
  • 10
    `kivy.core.window` have a `on_dropfile` event that is dispatched when a file is dropped on the application, here's the event handler https://kivy.org/docs/api-kivy.core.window.html?highlight=window#kivy.core.window.WindowBase.on_dropfile – hchandad Jun 01 '16 at 16:25

1 Answers1

19

Use on_dropfile event handler. Here is an working example:

from kivy.app import App
from kivy.core.window import Window


class WindowFileDropExampleApp(App):
    def build(self):
        Window.bind(on_dropfile=self._on_file_drop)
        return

    def _on_file_drop(self, window, file_path):
        print(file_path)
        return

if __name__ == '__main__':
    WindowFileDropExampleApp().run()
avi
  • 9,292
  • 11
  • 47
  • 84
  • I tried this code on command line with sudo. sudo kivy dnd.py. it doesn't work on my mac. (Provider: sdl2 / Kivy:v1.9.0, / python:v2.7.10 / OS x Sierra ) – Jinbom Heo Sep 20 '17 at 11:08
  • Works as expected on Windows 10 – Jean-Pierre Schnyder Mar 27 '18 at 16:19
  • 1
    Is there a way to drag a file *out* of Kivy into another application? For example you can drag a file from PyCharm. – Avi Shah Oct 18 '21 at 02:07
  • @AviShah I don't believe dragging out of Kivy is possible. Here is a GitHub issue that is tracking that feature: https://github.com/kivy/kivy/issues/3557 – mihow May 31 '22 at 00:08
  • "Deprecated in 2.1.0, use on_drop_file event instead. Event on_dropfile will be removed in the next two releases..." - Kivy 2.1.0. The event callback has also changed. – demberto Nov 09 '22 at 07:26