怎么用python的tk做文件拖拽
时间: 2023-11-11 21:03:31 浏览: 30
在Python的Tkinter模块中,可以使用`bind`方法来绑定事件,通过`<Button-1>`事件可以实现鼠标左键拖拽文件并将其路径显示在文本框中。
以下是一个简单的示例代码:
```python
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
# 创建文本框
text = tk.Text(root)
text.pack()
# 绑定拖拽事件
def drag_file(event):
# 获取拖拽的文件路径
file_path = root.tk.call('dragging', 'info', 'files')
# 将路径显示在文本框中
text.insert('end', file_path + '\n')
# 绑定拖拽事件
text.bind('<Button-1>', lambda e: root.tk.call('dragging', 'site', 'set', e.x_root, e.y_root))
text.bind('<ButtonRelease-1>', lambda e: root.tk.call('dragging', 'site', 'stop'))
text.bind('<B1-Motion>', lambda e: root.tk.call('dragging', 'site', 'move', e.x_root, e.y_root))
text.bind('<DragEnter>', lambda e: e.widget.focus_force())
text.bind('<DragLeave>', lambda e: e.widget.focus())
text.bind('<DragB1-Motion>', drag_file)
root.mainloop()
```
上述代码中,我们通过`tk.call`方法调用了一个名为`dragging`的内置Tcl/Tk命令,用于处理拖拽事件。在`<Button-1>`事件中,我们将鼠标点击的位置保存在拖拽对象中;在`<B1-Motion>`事件中,我们将鼠标移动的位置更新到拖拽对象中;在`<DragB1-Motion>`事件中,我们获取拖拽的文件路径并将其显示在文本框中。
需要注意的是,上述代码在Windows系统上运行时需要安装Tcl/Tk库,并且需要将tcl86t.dll和tk86t.dll文件复制到Python安装目录的tcl目录下。