如何使用 tkFileDialog(Tkinter) 获取文件的绝对路径?
Tkinter 是一个标准的 Python 库,用于创建和开发功能性和特色应用程序。它具有各种内置函数、模块和包,可用于构建应用程序的逻辑。
tkFileDialog 是 Tkinter 库中可用的一个内置模块,可用于与系统文件和目录进行交互。但是,一旦我们使用 tkFileDialog 以读取模式选择特定文件,则可以进一步使用它来处理文件中可用的信息。
如果希望在应用程序加载文件时访问文件的绝对路径,可以使用 OS 模块的可用函数,即 os.path.abspath(file.name) 函数。此函数将返回文件的绝对路径,该路径可以存储在变量中,以便在窗口或屏幕上显示。
示例
# Import the required Libraries
from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile
import os
# Create an instance of tkinter frame
win = Tk()
# Set the geometry of tkinter frame
win.geometry("700x350")
def open_file():
file = filedialog.askopenfile(mode='r', filetypes=[('Python Files', '*.py')])
if file:
filepath = os.path.abspath(file.name)
Label(win, text="The File is located at : " + str(filepath), font=('Aerial 11')).pack()
# Add a Label widget
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13'))
label.pack(pady=10)
# Create a Button
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)
win.mainloop()输出
运行代码时,它将首先显示以下窗口:
现在,单击“浏览”按钮并从资源管理器中选择一个 Python 文件。它将显示您选择的文件的绝对路径。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP