Tkinter เป็นไลบรารีมาตรฐานของ Python สำหรับสร้างและพัฒนาแอปพลิเคชัน มีฟังก์ชัน โมดูล และแพ็กเกจในตัวมากมาย
tkFileDialog เป็นโมดูลในตัวในไลบรารี Tkinter ใช้สำหรับโต้ตอบกับไฟล์และไดเรกทอรีของระบบ เมื่อเลือกไฟล์ในโหมดอ่านด้วย tkFileDialog สามารถนำไปประมวลผลข้อมูลในไฟล์ต่อได้
หากต้องการเข้าถึง absolute path ของไฟล์เมื่อโหลดในแอปพลิเคชัน ให้ใช้ฟังก์ชันของโมดูล OS คือ os.path.abspath(file.name) ฟังก์ชันนี้จะคืนค่า absolute path ซึ่งสามารถเก็บในตัวแปรเพื่อแสดงในหน้าต่างได้
ตัวอย่าง
# 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()ผลลัพธ์
การรันโค้ดจะแสดงหน้าต่างดังนี้

คลิกปุ่ม "Browse" และเลือกไฟล์ Python จาก Explorer จะแสดง absolute path ของไฟล์ที่เลือก
