Tkinter askdirectory() 方法

  1. Python 中的 Tkinter
  2. 在 Tkinter 中使用 askdirectory() 方法開啟檔案對話方塊
Tkinter askdirectory() 方法

本教程將討論 Python 的圖形使用者介面,特別是使用 tkinter。然後我們將看看如何使用 askdirectory() 方法在你的 PC 上開啟一個目錄。

Python 中的 Tkinter

Tkinter 是 Python 中的一個內建模組,它允許使用者相對輕鬆快速地建立 GUI(圖形使用者介面)。tkinter 庫主要依賴於元件。

有按鈕元件、文字元件、框架元件,一切都是元件,而你建立的第一件事就是根元件。這個元件就像一個視窗,你計算機上的任何圖形使用者介面程式都有一個視窗。

特殊的 GUI 元素允許使用者瀏覽檔案系統並選擇檔案路徑。使用者可以在特定檔案路徑開啟檔案或將檔案儲存在特定檔案路徑。

我們可以通過各種不同的檔案對話方塊來做到這一點。檔案對話方塊不止一個,但我們將看一下 askdirectory() 方法。

在 Tkinter 中使用 askdirectory() 方法開啟檔案對話方塊

askdirectory() 帶有 tkinter 中的 filedialog 類。askdirectory() 方法包括一個對話方塊,該對話方塊只允許使用者選擇的目錄和返回目錄路徑。

使用 askdirectory() 方法,首先從 tkinter 模組匯入 filedialog

Python
 pythonCopyfrom tkinter import filedialog

我們將建立 ButtonLabel 元件。該按鈕將觸發我們的檔案對話方塊,所以基本上,當我們單擊按鈕時,檔案對話方塊就會觸發。

我們已將 directory 函式傳遞到命令引數中。我們將在 directory 函式中工作。

Python
 pythonCopydialog_btn = Button(gui_win, text="select directory", command=get_directories)
dialog_btn.pack()

現在我們建立了一個 directory 函式,因此該函式有助於使用該方法獲取目錄路徑。該方法採用 initialdirtitle 引數。

initialdir 引數指定你要開啟對話方塊的位置,title 引數是你的對話方塊標題。askdirectory() 方法返回字串中的目錄路徑,因此我們將返回值儲存在 label_path 變數中,並將其設定在標籤中以顯示所選路徑。

Python
 pythonCopydef directory():
    # get a directory path by user
    filepath = filedialog.askdirectory(
        initialdir=r"F:\python\pythonProject", title="Dialog box"
    )
    label_path = Label(gui_win, text=filepath, font=("italic 14"))
    label_path.pack(pady=20)

完整的原始碼:

Python
 pythonCopyfrom tkinter import *
from tkinter import filedialog

gui_win = Tk()
gui_win.geometry("400x200")
gui_win.grid_rowconfigure(0, weight=1)
gui_win.grid_columnconfigure(0, weight=1)


def directory():
    # get a directory path by user
    filepath = filedialog.askdirectory(
        initialdir=r"F:\python\pythonProject", title="Dialog box"
    )
    label_path = Label(gui_win, text=filepath, font=("italic 14"))
    label_path.pack(pady=20)


dialog_btn = Button(gui_win, text="select directory", command=directory)
dialog_btn.pack()

gui_win.mainloop()

輸出:

在 Tkinter 中使用 askdirectory() 方法開啟檔案對話方塊

單擊此處以閱讀有關 askdirectory() 方法的更多資訊。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Salman Mehmood
Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn