如何使用 tkFileDialog(Tkinter) 獲取檔案的絕對路徑?
Tkinter 是一個標準的 Python 庫,用於建立和開發功能性和特色應用程式。它具有各種內建函式、模組和包,可用於構建應用程式的邏輯。
tkFileDialog 是 Tkinter 庫中可用的一個內建模組,可用於與系統檔案和目錄進行互動。但是,一旦我們使用 tkFileDialog 以讀取模式選擇特定檔案,則可以進一步使用它來處理檔案中可用的資訊。
如果希望在應用程式載入檔案時訪問檔案的絕對路徑,可以使用 OS 模組的可用函式,即 os.path.abspath(file.name) 函式。此函式將返回檔案的絕對路徑,該路徑可以儲存在變數中,以便在視窗或螢幕上顯示。
示例
# Import the required Libraries from tkinter import * from tkinter import ttk, filedialog from tkinter.filedialog import askopenfile import os # Create an instance of tkinter frame win = Tk() # Set the geometry of tkinter frame win.geometry("700x350") def open_file(): file = filedialog.askopenfile(mode='r', filetypes=[('Python Files', '*.py')]) if file: filepath = os.path.abspath(file.name) Label(win, text="The File is located at : " + str(filepath), font=('Aerial 11')).pack() # Add a Label widget label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13')) label.pack(pady=10) # Create a Button ttk.Button(win, text="Browse", command=open_file).pack(pady=20) win.mainloop()
輸出
執行程式碼時,它將首先顯示以下視窗:
現在,單擊“瀏覽”按鈕並從資源管理器中選擇一個 Python 檔案。它將顯示您選擇的檔案的絕對路徑。
廣告