由tkinter写成,可实现拖动桌面pdf文件或者文件夹中的pdf文件,放入展示框,并展示绝对路径,可用在Python的GUI界面中,实现用户快速单一或批量选择大量文件。
此外,可修改源码中的文件后缀名,选择其他所需要的文件。
效果图:
源码:
from tkinter import *
import re
class TkDnD:
def __init__(self, tkroot):
self._tkroot = tkroot
tkroot.tk.eval('package require tkdnd')
tkroot.dnd = self
def bindsource(self, widget, type=None, command=None, arguments=None, priority=None):
command = self._generate_callback(command, arguments)
tkcmd = self._generate_tkcommand('bindsource', widget, type, command, priority)
res = self._tkroot.tk.eval(tkcmd)
if type == None:
res = res.split()
return res
def bindtarget(self, widget, type=None, sequence=None, command=None, arguments=None, priority=None):
command = self._generate_callback(command, arguments)
tkcmd = self._generate_tkcommand('bindtarget', widget, type, sequence, command, priority)
res = self._tkroot.tk.eval(tkcmd)
if type == None:
res = res.split()
return res
def clearsource(self, widget):
self._tkroot.tk.call('dnd', 'clearsource', widget)
def cleartarget(self, widget):
self._tkroot.tk.call('dnd', 'cleartarget', widget)
def drag(self, widget, actions=None, descriptions=None, cursorwindow=None, command=None, arguments=None):
command = self._generate_callback(command, arguments)
if actions:
if actions[1:]:
actions = '-actions {%s}' % ' '.join(actions)
else:
actions = '-actions %s' % actions[0]
if descriptions:
descriptions = ['{%s}' % i for i in descriptions]
descriptions = '{%s}' % ' '.join(descriptions)
if cursorwindow:
cursorwindow = '-cursorwindow %s' % cursorwindow
tkcmd = self._generate_tkcommand('drag', widget, actions, descriptions, cursorwindow, command)
self._tkroot.tk.eval(tkcmd)
def _generate_callback(self, command, arguments):
cmd = None
if command:
cmd = self._tkroot._register(command)
if arguments:
cmd = '{%s %s}' % (cmd, ' '.join(arguments))
return cmd
def _generate_tkcommand(self, base, widget, *opts):
tkcmd = 'dnd %s %s' % (base, widget)
for i in opts:
if i is not None:
tkcmd += ' %s' % i
return tkcmd
# 将拖入的文件添加到listbox中
def drop(files):
if isinstance(files, str):
files = re.sub(u"{.*?}", "", files).split() # 通过空格切分多文件,所以文件名中不能有空格
for file in files:
if file.endswith('.pdf'):
#添加到列表
lb.insert("end", file)
if __name__ == '__main__':
window = Tk()
window.geometry('800x500') # 位置设置
window.wm_resizable(False, False) # 不允许修改长宽
dnd = TkDnD(window)
# #列表控件
lb = Listbox(window, height=10, width=60, selectmode=SINGLE)
dnd.bindtarget(lb, 'text/uri-list', '<Drop>', drop, ('%D',))
lb.place(relx=0.20, rely=0.12)
window.mainloop()