Trong hầu hết trường hợp, callback function tham chiếu Instance Method. Instance method truy cập thành viên và thao tác không cần đối số.
Xét trường hợp nhiều component định nghĩa, muốn xử lý sự kiện với các component. Chạy nhiều sự kiện, truyền nhiều đối số cho event handlers.
Ví dụ
Tạo nhiều nút trong frame, xử lý sự kiện truyền tên widget làm đối số. Bấm nút cập nhật Label.
#Import Tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
#Tạo instance Tkinter frame
win= Tk()
#Đặt geometry
win.geometry("750x250")
#Định nghĩa Event handlers cho các Operation
def event_low(button1):
label.config(text="This is Lower Value")
def event_mid(button2):
label.config(text="This is Medium Value")
def event_high(button3):
label.config(text="This is Highest value")
#Tạo Label
label= Label(win, text="",font=('Helvetica 15 underline'))
label.pack()
#Tạo frame
frame= Frame(win)
#Tạo Buttons trong frame
button1= ttk.Button(frame, text="Low", command=lambda:event_low(button1))
button1.pack(pady=10)
button2= ttk.Button(frame, text="Medium",command= lambda:event_mid(button2))
button2.pack(pady=10)
button3= ttk.Button(frame, text="High",command= lambda:event_high(button3))
button3.pack(pady=10)
frame.pack()
win.mainloop()
Kết quả
Chạy mã hiển thị cửa sổ nút Low, Medium, High. Bấm nút hiển thị label text.
