Tkinter เป็นไลบรารี Python มาตรฐานที่ใช้ในการสร้างและพัฒนาแอปพลิเคชันที่ใช้งานได้และโดดเด่น มีฟังก์ชัน โมดูล และแพ็คเกจในตัวที่หลากหลาย ที่สามารถใช้สร้างตรรกะของแอปพลิเคชันได้
tkFileDialog เป็นโมดูล inbuilt ที่มีอยู่ในไลบรารี 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 จาก Explorer มันจะแสดงเส้นทางที่แน่นอนของไฟล์ที่คุณเลือก
