Tkinter Askopenfilename

您所在的位置:网站首页 askopenfilenames顺序 Tkinter Askopenfilename

Tkinter Askopenfilename

2024-07-11 01:33| 来源: 网络整理| 查看: 265

本文将演示如何使用文件对话框使用 filedialog 类中的 askopenfilename() 方法打开文件。无论文件在你的计算机上的什么位置。

当我们处理现实世界的 GUI 应用程序并希望添加一个文件对话框功能来打开文件(图像、PDF 文件或任何东西)时,你如何使用 Tkinter 做到这一点?使用称为 filedialog 类的东西真的很容易。

在 Tkinter 中使用 askopenfilename() 方法打开文件对话框

askopenfilename() 负责在 Tkinter GUI 应用程序中打开和读取文件;此方法存在于 filedialog 类中。

所以首先,我们需要导入这个类,如下所示。

from tkinter import filedialog

创建 Tk() 类的实例后,我们需要在我们的 GUI 中添加一个按钮,因此当我们单击此按钮时,它将启动一个文件对话框,我们可以选择我们的文件。

open_btn = Button(text="Open", command=openFile) open_btn.pack()

我们创建了一个帮助打开文件对话框的 openFile() 函数。我们正在使用 filedialog 类中的方法。

def openFile(): # takes file location and its type file_location = filedialog.askopenfilename( initialdir=r"F:\python\pythonProject\files", title="Dialog box", filetypes=(("text files", "*.txt"), ("all files", "*.*")), ) # read selected file by dialog box file = open(file_location, "r") print(file.read()) file.close()

在这个方法中,我们必须传递一堆不同的选项。

initialdir:此选项告诉对话框要从哪个目录开始,因此该框会弹出你要显示的目录,因此你应该使用此选项。 title:这只是弹出框的标题。它的顶部会有一个小标题,你可以放任何你想要的东西。 filetypes:此选项有助于选择要显示的文件类型。你可以只放置所有文件,特别是 .txt 文件或其他文件扩展名。

askopenfilename() 方法返回一个字符串,该字符串是你的文件所在的文件路径,因此我们将文件路径存储在一个名为 file_location 的变量中。

现在我们将打开并读取该文件的内容以创建一个文件变量,并且我们使用了接受文件路径和模式的 open 函数。

我们使用 "r" 模式以阅读模式打开文件。read() 方法有助于读取整个内容并将其显示在控制台中。

完整的源代码在这里。

from tkinter import * from tkinter import filedialog def openFile(): # takes file location and its type file_location = filedialog.askopenfilename( initialdir=r"F:\python\pythonProject\files", title="Dialog box", filetypes=(("text files", "*.txt"), ("all files", "*.*")), ) # read selected file by dialog box file = open(file_location, "r") print(file.read()) file.close() gui_win = Tk() gui_win.geometry("200x200") gui_win.title("Delftstack") open_btn = Button(text="Open", command=openFile) open_btn.pack() gui_win.mainloop()

输出:



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3