Python3 文件选择对话框:使用 tkinter 创建文件路径输入框
在 Python 中,可以使用 'tkinter' 模块创建 GUI 应用程序。以下是一个基本的文件选择对话框示例:
import tkinter as tk
from tkinter import filedialog
def select_file():
file_path = filedialog.askopenfilename()
if file_path:
print('Selected file:', file_path)
root = tk.Tk()
button = tk.Button(root, text='Select File', command=select_file)
button.pack()
root.mainloop()
在这个例子中,我们创建了一个 'Tk' 对象 'root',并在其上放置了一个按钮 'button'。当用户单击按钮时,'select_file()' 函数将被调用。该函数使用 'filedialog.askopenfilename()' 方法显示一个文件选择对话框,并返回用户选择的文件路径。如果用户取消了选择,则返回空字符串。
你可以根据自己的需要修改此示例,例如更改按钮文本、更改默认目录、添加文件类型过滤等等。
原文地址: https://www.cveoy.top/t/topic/nDyT 著作权归作者所有。请勿转载和采集!