Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเปิดและอ่านไฟล์ด้วย askopenfilename ใน Tkinter

การใช้ filedialog.askopenfilename() ใน Tkinter เพื่อเปิด Dialog ให้ผู้ใช้เลือกไฟล์ แล้วอ่านเนื้อหาแสดงใน Label Widget

ขั้นตอนการทำงาน

  1. นำเข้า tkinter, ttk, filedialog
  2. สร้างฟังก์ชัน open_files():
    • เรียก filedialog.askopenfilename() ได้ path
    • เปิดไฟล์อ่านด้วย open(path, 'r')
    • อ่านเนื้อหา file.read()
    • แสดงใน Label, ปิดไฟล์, ปิดปุ่ม, ปรับขนาดหน้าต่าง
  3. สร้าง 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
filetypesTuple of (description, pattern) เช่น (("Text", "*.txt"), ("All", "*.*"))
initialdirโฟลเดอร์เริ่มต้น
parentParent window
multipleTrue = เลือกหลายไฟล์ (คืน 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