tkinter实现拖动文件放入展示框

        由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()

Python中,可以使用Tkinter库来创建简单的图形用户界面,并实现放功能。要实现拖动文件Tkinter窗口中的文件浏览框(如`Entry`或`Text`)并在文本框中显示文件路径,你需要做以下几步: 1. 首先,导入必要的模块: ```python import tkinter as tk from tkinter import filedialog ``` 2. 创建主窗口文件输入框: ```python root = tk.Tk() file_path_entry = tk.Entry(root) file_path_entry.pack() ``` 3. 添加鼠标按下事件监听,用于开始放操作: ```python def start_dragging(event): # 在这里添加一个标记,表示已经开始放 file_path_entry["state"] = "disabled" # 禁止用户输入 file_path_entry.bind("<ButtonPress-1>", start_dragging) ``` 4. 添加鼠标释放事件监听,处理文件入事件: ```python def end_dragging(event): # 检查是否有文件放到窗口上 dropped_files = event.widget.clipboard_get() # 获取剪贴板内容 if dropped_files: # 解析文件路径 file_path = filedialog.askopenfilename(filetypes=(("All Files", "*.*"),), initialdir="/") # 显示打开文件对话框 if file_path: file_path_entry.delete(0, tk.END) # 清空文本框 file_path_entry.insert(0, file_path) # 插入文件路径 file_path_entry["state"] = "normal" # 重置为正常状态,允许用户继续输入 file_path_entry.bind("<ButtonRelease-1>", end_dragging) ``` 5. 最后,启动主循环: ```python root.mainloop() ``` 现在,当用户点击并拖动文件到这个窗口文件输入框区域,然后松开鼠标,会弹出一个选择文件的对话框,用户可以选择文件后,文件路径就会出现在文本框中。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值