在Python中,你可以使用`tkinter`和`filedialog`模块来创建一个图形用户界面(GUI),让用户能够方便地选择文件或目录路径。以下是一个简单的示例代码,展示了如何实现这一功能:
import tkinter as tkfrom tkinter import filedialogdef select_file():弹出对话框让用户选择文件,并返回文件的完整路径root = tk.Tk()root.withdraw() 关闭根窗口file_path = filedialog.askopenfilename() 打开文件对话框return file_pathdef select_directory():弹出对话框让用户选择目录,并返回目录的完整路径root = tk.Tk()root.withdraw() 关闭根窗口directory_path = filedialog.askdirectory() 打开目录对话框return directory_path选择文件file_path = select_file()print('选择的文件路径是:', file_path)选择目录directory_path = select_directory()print('选择的目录路径是:', directory_path)
运行上述代码,会弹出一个文件选择对话框,用户可以选择一个文件,然后程序会打印出该文件的路径。同样,也可以选择目录,并打印出所选目录的路径。

