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

วิธีจับเหตุการณ์บน Tkinter Child Widgets


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

ตัวอย่าง

ในตัวอย่างนี้ สร้าง Listbox widget ที่มีรายการไอเท็ม เมื่อเลือกไอเท็ม จะจับว่าผู้ใช้คลิกอะไร ใช้ฟังก์ชัน print() เพื่อพิมพ์บนหน้าจอ

# Import the required libraries
from tkinter import *
from tkinter import ttk

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

# Create a Listbox widget
lb=Listbox(win)
lb.pack(expand=True, fill=BOTH)

# Define a function to edit the listbox item
def save():
    for item in lb.curselection():
        print("You have selected "+ str(item+1))

# Add items in the Listbox
lb.insert("end","item1","item2","item3","item4","item5")

# Add a Button To Edit and Delete the Listbox Item
ttk.Button(win, text="Save", command=save).pack()

win.mainloop()

ผลลัพธ์

การรันโค้ดจะแสดงหน้าต่างพร้อมรายการไอเท็ม หากคลิกปุ่ม "Save" จะบอกว่าเหตุการณ์ใดถูกจับ

วิธีจับเหตุการณ์บน Tkinter Child Widgets

เลือกไอเท็มจากรายการและคลิก "Save" จะพิมพ์ไอเท็มที่เลือกบนคอนโซล

You have selected 3