Open Pin-Jiun opened 1 year ago
最簡單的使用方法像這樣
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
print(file_path)
filedialog.askopenfilename() 會回傳的類型為 str,若取消的話會回傳一個空的 tuple ()
tkinter filedialog 設定開啟檔案對話框的標題 filedialog 想要設定一些提示訊息在開啟檔案對話框的標題,來提示使用者到底要開什麼檔案的話, 可以在 filedialog.askopenfilename() 參數裡指定 title,實際上就會寫成這樣
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(parent=root,
title='Select file')
tkinter filedialog 指定一個初始的目錄來開啟檔案 通常會有個初始的目錄讓使用者去選,但預設的目錄可能離最終目標的目錄差很多層,這樣使用者要點很多次,很不方便,所以會給一個初始目錄
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(parent=root,
initialdir='~/')
tkinter filedialog 設定開啟的檔案類型 假設使用者只想開啟圖片類型的檔案,又不想看到一堆非圖片類型的檔案例如像 .txt 或其他類型, 否則使用者在選擇檔案時會找很慢,所以有些情況下會去設定開啟的檔案類型,這有助於加速使用者開啟檔案, 可以在 filedialog.askopenfilename() 參數裡指定 filetypes,像這樣
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(parent=root,
filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
如果要改成開啟資料夾, 可以使用
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
The following steps are involved in creating a tkinter application:
Importing the Tkinter module. Creation of the main window (container). Addition of widgets to the main window Applying the event Trigger on widgets like buttons, etc.
File dialogs
File dialogs help you open, save files or directories. This is the type of dialog you get when you click file,open. This dialog comes out of the module, there’s no need to write all the code manually.
https://www.geeksforgeeks.org/file-explorer-in-python-using-tkinter/