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

การสร้างปุ่ม Browse ด้วย Tkinter


เพื่อสร้างปุ่มในแอปพลิเคชัน Tkinter ให้ใช้ Widget Button ปุ่มใช้สำหรับประมวลผลการทำงานของเหตุการณ์ในรันไทม์ สร้างปุ่มได้โดยกำหนดคอนสตรัคเตอร์ Button(parent, text, **options)

สมมติว่าต้องการสร้างปุ่ม Browse ซึ่งเมื่อคลิกจะขอให้ผู้ใช้เลือกไฟล์จากระบบ explorer สร้างกล่องโต้ตอบเลือกไฟล์ได้ด้วยแพ็กเกจ filedialog ในไลบรารี tkinter นำเข้า filedialog ด้วยคำสั่ง:

from tkinter import filedialog

เมื่อนำเข้าแพ็กเกจแล้ว สามารถใช้สร้างกล่องโต้ตอบเปิดและเลือกไฟล์ Python ทั้งหมด และคืนค่าจำนวนตัวอักษรในไฟล์นั้น

ตัวอย่าง

# Import the required Libraries
from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile

# 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:
        content = file.read()
        file.close()
        print("%d characters in this file" % len(content))

# 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()

ผลลัพธ์

รันโค้ดเพื่อเรียกดูและเลือกไฟล์จาก system explorer

การสร้างปุ่ม Browse ด้วย Tkinter