如何在 tkinter 的 filedialog 中指定檔案路徑?
Tkinter 提供了幾個內建函式和類庫方法來構建應用程式的元件和使用者可操作專案。filedialog 是 tkinter 模組之一,它提供類和庫函式來建立檔案/目錄選擇視窗。您可以在需要提示使用者從系統瀏覽檔案或目錄的地方使用filedialog。
您還可以指定應從中提取特定檔案的目錄位置。要顯示從特定位置開始的 filedialog,請在靜態工廠函式 askopenfilename(initialdir=<location>) 中使用 initialdir = <location> 引數。此函式建立一個模態對話方塊,等待使用者的選擇並將所選檔案的值返回給呼叫方。
示例
讓我們建立一個應用程式,要求使用者從系統目錄中選擇一個檔案。
# Import required libraries
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
# Create an instance of tkinter window
win = Tk()
win.geometry("700x350")
# Create an instance of style class
style=ttk.Style(win)
def open_win_diag():
# Create a dialog box
file=filedialog.askopenfilename(initialdir="C:/")
f=open(win.file, 'r')
# Create a label widget
label=Label(win, text= "Click the button to browse the file", font='Arial 15 bold')
label.pack(pady= 20)
# Create a button to open the dialog box
button=ttk.Button(win, text="Open", command=open_win_diag)
button.pack(pady=5)
win.mainloop()輸出
執行以上程式碼將顯示一個包含兩個部件的視窗。

按鈕部件觸發檔案對話方塊,提示使用者從系統瀏覽檔案。

我們在 askopenfilename() 函式中指定了 "initialdir=C:/"。因此,它將 C 盤作為初始目錄開啟。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP