| FAQ Index - Search - Recent Changes - Everything - Add entry |
23.31. How to get the path to the file(s)/folder(s) that was dropped (by drag 'n' drop) in my application? [using selection.data]
You connect like that:
widget.connect('drag_data_received', on_drag_data_received)
and in your callback you do:
def on_drag_data_received(widget, context, x, y, selection, target_type, timestamp):
uri = selection.data.strip('\r\n\x00')
uri_splitted = uri.split() # we may have more than one file dropped
for uri in uri_splitted:
path = get_file_path_from_dnd_dropped_uri(uri)
if os.path.isfile(path): # is it file?
data = file(path).read()
print data
def get_file_path_from_dnd_dropped_uri(uri):
# get the path to file
path = ""
if uri.startswith('file:\\\\\\'): # windows
path = uri[8:] # 8 is len('file:///')
elif uri.startswith('file://'): # nautilus, rox
path = uri[7:] # 7 is len('file://')
elif uri.startswith('file:'): # xffm
path = uri[5:] # 5 is len('file:')
path = urllib.url2pathname(path) # escape special chars
path = path.strip('\r\n\x00') # remove \r\n and NULL
return path
Real life example:
import gtk
import urllib
import os
TARGET_TYPE_URI_LIST = 80
dnd_list = [ ( 'text/uri-list', 0, TARGET_TYPE_URI_LIST ) ]
def get_file_path_from_dnd_dropped_uri(uri):
# get the path to file
path = ""
if uri.startswith('file:\\\\\\'): # windows
path = uri[8:] # 8 is len('file:///')
elif uri.startswith('file://'): # nautilus, rox
path = uri[7:] # 7 is len('file://')
elif uri.startswith('file:'): # xffm
path = uri[5:] # 5 is len('file:')
path = urllib.url2pathname(path) # escape special chars
path = path.strip('\r\n\x00') # remove \r\n and NULL
return path
def on_drag_data_received(widget, context, x, y, selection, target_type, timestamp):
if target_type == TARGET_TYPE_URI_LIST:
uri = selection.data.strip('\r\n\x00')
print 'uri', uri
uri_splitted = uri.split() # we may have more than one file dropped
for uri in uri_splitted:
path = get_file_path_from_dnd_dropped_uri(uri)
print 'path to open', path
if os.path.isfile(path): # is it file?
data = file(path).read()
#print data
w = gtk.Window()
w.connect('drag_data_received', on_drag_data_received)
w.drag_dest_set( gtk.DEST_DEFAULT_MOTION |
gtk.DEST_DEFAULT_HIGHLIGHT | gtk.DEST_DEFAULT_DROP,
dnd_list, gtk.gdk.ACTION_COPY)
w.show_all()
gtk.main()
