การใช้ filedialog.askopenfilename() ใน Tkinter เพื่อเปิด Dialog ให้ผู้ใช้เลือกไฟล์ แล้วอ่านเนื้อหาแสดงใน Label Widget
ขั้นตอนการทำงาน
- นำเข้า
tkinter,ttk,filedialog - สร้างฟังก์ชัน
open_files():- เรียก
filedialog.askopenfilename()ได้ path - เปิดไฟล์อ่านด้วย
open(path, 'r') - อ่านเนื้อหา
file.read() - แสดงใน Label, ปิดไฟล์, ปิดปุ่ม, ปรับขนาดหน้าต่าง
- เรียก
- สร้าง Label ว่าง และ Button เรียก
open_files
ตัวอย่างโค้ด
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
win = Tk()
win.geometry("750x150")
def open_files():
path = filedialog.askopenfilename(title="Select a file",
filetypes=(("text files", "*.txt"), ("all files", "*.*")))
if path:
with open(path, 'r') as file:
txt = file.read()
label.config(text=txt, font=('Courier 13 bold'))
button.config(state=DISABLED)
win.geometry("750x450")
label = Label(win, text="", font=('Courier 13 bold'))
label.pack()
button = ttk.Button(win, text="Open", command=open_files)
button.pack(pady=30)
win.mainloop()
พารามิเตอร์ askopenfilename()
| พารามิเตอร์ | คำอธิบาย |
|---|---|
title | หัวข้อ Dialog |
filetypes | Tuple of (description, pattern) เช่น (("Text", "*.txt"), ("All", "*.*")) |
initialdir | โฟลเดอร์เริ่มต้น |
parent | Parent window |
multiple | True = เลือกหลายไฟล์ (คืน tuple) |
ฟังก์ชัน File Dialog อื่นๆ
askopenfile()- คืน File Object เปิดอยู่แล้วaskopenfilenames()- เลือกหลายไฟล์ (คืน Tuple)asksaveasfilename()- Dialog บันทึกไฟล์asksaveasfile()- คืน File Object สำหรับเขียนaskdirectory()- เลือกโฟลเดอร์
Best Practice: ใช้ with statement
with open(path, 'r', encoding='utf-8') as file:
content = file.read()
# ไฟล์ปิดอัตโนมัติ แม้จะเกิด Exception
การจัดการ Encoding
# พยายามอ่านหลาย encoding
encodings = ['utf-8', 'cp874', 'latin-1', 'cp1252']
for enc in encodings:
try:
with open(path, 'r', encoding=enc) as f:
content = f.read()
break
except UnicodeDecodeError:
continue
การประยุกต์ใช้
พื้นฐานของ: Text Editor, Log Viewer, Config File Editor, Data Import Tool, Script Runner