如何在 Tkinter 中使用 askdirectory 對話方塊建立新資料夾?
要使用 Tkinter 中的 **askdirectory** 對話方塊建立新資料夾,我們可以採取以下步驟:
匯入所需的模組。**filedialog** 模組是 **askdirectory** 方法所必需的。**os** 模組是 makedirs 方法所必需的。
建立 Tkinter 框架的例項。
使用 **win.geometry** 方法設定框架的大小。
定義使用者自定義方法 **“create_subfolder”**。在方法內部,呼叫 **filedialog.askdirectory** 選擇資料夾並將路徑儲存在變數 **source_path** 中。
我們可以使用 **filedialog** 的 **askdirectory** 方法開啟目錄。將所選目錄的路徑儲存在 **'path'** 變數中。
然後,使用 **os.path.join** 和 makedirs 在父目錄中建立子資料夾。
建立一個按鈕來呼叫 **create_subfolder** 方法。
示例
# Import the required libraries from tkinter import * from tkinter import ttk from tkinter import filedialog import os # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") def create_subfolder(): source_path = filedialog.askdirectory(title='Select the Parent Directory') path = os.path.join(source_path, 'Images') os.makedirs(path) button1 = ttk.Button(win, text="Select a Folder", command=create_subfolder) button1.pack(pady=5) win.mainloop()
輸出
當我們執行上述程式碼時,它將首先顯示以下視窗:
現在,單擊“選擇資料夾”按鈕以選擇父資料夾。它將在選定的父資料夾中自動建立一個名為“Images”的子資料夾。
廣告