python程序生成一个交互式对话框,用户将3个文件拖入框中可以获取文件路径,并将路径写入一个txt文档
时间: 2024-03-01 10:52:39 浏览: 24
可以使用 Python 的 `tkinter` 模块来生成交互式对话框,使用 `filedialog` 子模块来让用户选择文件,并使用 `os` 模块来获取文件路径和判断文件是否存在。具体实现如下:
```python
import tkinter as tk
from tkinter import filedialog
import os
# 创建主窗口
root = tk.Tk()
root.withdraw()
# 打开文件对话框
file_paths = filedialog.askopenfilenames()
# 判断文件是否存在
exist_files = []
for file_path in file_paths:
if os.path.exists(file_path):
exist_files.append(file_path)
else:
print(f'文件 {file_path} 不存在')
# 创建并打开 txt 文件
with open('file_paths.txt', 'w') as f:
# 写入文件路径
for file_path in exist_files:
f.write(file_path + '\n')
print('文件路径已写入 file_paths.txt')
```
以上代码会生成一个交互式对话框,用户可以将多个文件拖入框中来选择文件。程序会判断文件是否存在,如果存在则将文件路径写入 `file_paths.txt` 文件中,否则输出错误信息。需要注意的是,由于 `tkinter` 是跨平台的图形界面库,因此可以在 Windows、macOS 和 Linux 等多个操作系统上运行。