1.需求
显示一个文件对话框,对话框列出了当前目录下的文件和目录,用于可以选择一个将要打开的文件名。如果文件名是有效的且该文件存在,则当用户点击Open时函数返回该文件名。若不存在,显示一个控制返回对话框值的错误提示信息,此时用户可以输入另外的文件名或点击Cancel按钮。如果用户点击Cancel按钮或关闭对话框,函数将返回0。
- 在写程序时,有时候需要处理的文件会很多,文件名的相似性不强。如果采取直接在程序中写死的方法,那么修改文件名过于繁琐,灵活性不强。
最近在stackoverflow看到有人提出这个问题。
2.解决方案
使用tkinter图形库
- Tkinter is the easiest way if you don’t want to have any other dependencies. To show only the dialog without any other GUI elements, you have to hide the root window using the withdraw method
Python 3
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filed