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

การเลือกโฟลเดอร์และเก็บพาธด้วย Tkinter ใน Python

การใช้ filedialog.askopenfilename() หรือ askdirectory() ใน Tkinter เพื่อให้ผู้ใช้เลือกไฟล์/โฟลเดอร์ แล้วนำ Path ไปใช้งานต่อ

ตัวอย่างโค้ด: เลือกไฟล์


from tkinter import *
from tkinter import ttk
from tkinter import filedialog

win = Tk()
win.geometry("750x250")

def select_file():
    path = filedialog.askopenfilename(title="Select a File",
        filetypes=(('Text Files', '*.txt'), ('All Files', '*.*')))
    if path:
        Label(win, text=path, font=13).pack()

Label(win, text="Click the Button to Select a File",
      font=('Arial 18 bold')).pack(pady=20)

button = ttk.Button(win, text="Select", command=select_file)
button.pack(ipadx=5, pady=15)

win.mainloop()

ตัวอย่างโค้ด: เลือกโฟลเดอร์ (askdirectory)


def select_folder():
    path = filedialog.askdirectory(title="Select a Folder",
                                   initialdir="/home/user/Documents")
    if path:
        Label(win, text=f"Selected: {path}", font=13).pack()
        # หรือเก็บใน Variable
        folder_var.set(path)

folder_var = StringVar()
ttk.Entry(win, textvariable=folder_var, width=60).pack()
ttk.Button(win, text="Browse Folder", command=select_folder).pack()

Filetypes Pattern


filetypes = [
    ("Text Files", "*.txt"),
    ("Python Files", "*.py"),
    ("Image Files", "*.jpg *.png *.gif *.bmp"),
    ("All Files", "*.*"),
]
# Pattern ใช้ Wildcard * และ ? (Single char)

การจัดการ Path แบบ Modern: pathlib


from pathlib import Path

def select_file():
    path = filedialog.askopenfilename(...)
    if path:
        p = Path(path)
        print(f"Name: {p.name}")
        print(f"Stem: {p.stem}")      # ชื่อไฟล์ไม่รวม Extension
        print(f"Suffix: {p.suffix}")  # .txt
        print(f"Parent: {p.parent}")  # โฟลเดอร์
        print(f"Absolute: {p.absolute()}")

การประยุกต์ใช้

File Open Dialog, Save As Dialog, Folder Browser, Project Directory Selector, Import/Export Data, Backup Location Picker