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

วิธีเปิดหลายชื่อไฟล์ใน Tkinter และเพิ่มชื่อไฟล์ลงในลิสต์


เพื่อเปิดไฟล์ดิอะล็อกในแอปพลิเคชัน Tkinter มีแพ็กเกจ tkfiledialog สร้างกล่องโต้ตอบโต้ตอบกับไฟล์ภายนอกบนระบบ เพื่อทำงานกับ filedialog ให้นำเข้าแพ็กเกจด้วยคำสั่ง:

import tkinter.filedialog as fd

เพื่อเปิด explorer ในหน้าต่าง ใช้ฟังก์ชัน askopenfilename(parent, title, **options) จะดึงหน้าต่างขึ้นและให้ผู้ใช้เลือกไฟล์จาก explorer เมื่อเปิดไฟล์แล้ว สามารถกำหนดฟังก์ชันพิมพ์รายการไฟล์ที่เลือกทั้งหมด

ตัวอย่าง

# Import the required libraries
from tkinter import *
from tkinter import ttk
import tkinter.filedialog as fd

# Create an instance of tkinter frame or window
win = Tk()
# Set the geometry of tkinter frame
win.geometry("700x350")

def open_file():
    file = fd.askopenfilenames(parent=win, title='Choose a File')
    print(win.splitlist(file))

# Add a Label widget
label = Label(win, text="Select the Button to Open the File", font=('Aerial 11'))
label.pack(pady=30)

# Add a Button Widget
ttk.Button(win, text="Select a File", command=open_file).pack()

win.mainloop()

ผลลัพธ์

การรันโค้ดจะแสดงหน้าต่างที่มีปุ่มและ Label Text widget

วิธีเปิดหลายชื่อไฟล์ใน Tkinter และเพิ่มชื่อไฟล์ลงในลิสต์

คลิกปุ่ม "Select a File" เพื่อเปิด Dialog เลือกไฟล์จาก Explorer

วิธีเปิดหลายชื่อไฟล์ใน Tkinter และเพิ่มชื่อไฟล์ลงในลิสต์