以下代碼來自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
直接就是絕對路徑了。