Python打开文件对话框

以下代码来自http://interactivepython.org/runestone/static/thinkcspy/GUIandEventDrivenProgramming/02_standard_dialog_boxes.html#file-chooser

import tkinter as tk
from tkinter import filedialog
import os

application_window = tk.Tk()

# 设置文件对话框会显示的文件类型
my_filetypes = [('all files', '.*'), ('text files', '.txt')]

# 请求选择文件夹/目录
answer = filedialog.askdirectory(parent=application_window,
                                 initialdir=os.getcwd(),
                                 title="Please select a folder:")

# 请求选择文件
answer = filedialog.askopenfilename(parent=application_window,
                                    initialdir=os.getcwd(),
                                    title="Please select a file:",
                                    filetypes=my_filetypes)

# 请求选择一个或多个文件
answer = filedialog.askopenfilenames(parent=application_window,
                                     initialdir=os.getcwd(),
                                     title="Please select one or more files:",
                                     filetypes=my_filetypes)

# 请求选择一个用以保存的文件
answer = filedialog.asksaveasfilename(parent=application_window,
                                      initialdir=os.getcwd(),
                                      title="Please select a file name for saving:",
                                      filetypes=my_filetypes)

有一点需要注意,开头的 from tkinter import filedialog 不能写为 from tkinter import *
代码中的answer直接就是绝对路径了。

猜你喜欢

转载自blog.csdn.net/sinat_41104353/article/details/82670133