📅  最后修改于: 2023-12-03 15:34:05.260000             🧑  作者: Mango
Python Tkinter is a module that is bundled with the Python programming language. It provides a simple way to create graphical user interfaces (GUIs) for desktop applications. One useful feature of Tkinter is its built-in FileDialog module, which allows users to select and open files or folders on their computer.
To use Tkinter FileDialog to select a folder, you can create an instance of the tkinter.filedialog.askdirectory()
function, which will open a dialog box and prompt the user to select a folder. Here's an example:
from tkinter import filedialog
import tkinter as tk
root = tk.Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
print("Selected folder:", folder_selected)
In this example, we import the filedialog
module from the tkinter
package and create a tkinter
window (with root = tk.Tk()
) to run the application in. We then call the askdirectory()
function on our filedialog
object, which displays a dialog box for the user to select a folder.
The root.withdraw()
function, called immediately after creating the window, causes the window to be hidden from view. This is done because the filedialog
function will create its own window for the user to select a folder.
Once the user selects a folder and clicks "OK", the path to the selected folder is returned by the askdirectory()
function. This path is stored in the folder_selected
variable and printed to the console.
Using Tkinter FileDialog, you can easily prompt users to select a folder in your Python desktop applications.