Tkinter askdirectory() 方法

  1. Python 中的 Tkinter
  2. 在 Tkinter 中使用 askdirectory() 方法打开文件对话框
Tkinter askdirectory() 方法

本教程将讨论 Python 的图形用户界面,特别是使用 tkinter。然后我们将看看如何使用 askdirectory() 方法在你的 PC 上打开一个目录。

ADVERTISEMENT

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