대부분의 경우 콜백 함수는 인스턴스 메서드(Instance Method) 형태로 정의할 수 있습니다. 인스턴스 메서드는 별도의 인수를 지정하지 않아도 자신이 속한 객체의 모든 멤버에 접근하여 다양한 작업을 수행할 수 있습니다.
그러나 여러 개의 위젯이 정의되어 있고, 각 위젯마다 서로 다른 이벤트를 처리해야 하는 상황이라면 이야기가 달라집니다. 이렇게 여러 이벤트를 동시에 처리해야 할 때는 이벤트 핸들러에 여러 개의 인수를 전달하는 방식이 매우 유용합니다.
예제 코드
다음 예제에서는 프레임 안에 여러 개의 버튼 위젯을 생성하고, 위젯 객체를 인수로 전달하여 각각의 이벤트를 처리합니다. 버튼을 클릭하면 해당 버튼에 맞는 메시지가 Label 위젯에 표시되는 구조입니다.
#Import the Tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry
win.geometry("750x250")
#Define Event handlers for different Operations
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")
#Create a Label
label= Label(win, text="",font=('Helvetica 15 underline'))
label.pack()
#Create a frame
frame= Frame(win)
#Create Buttons in the 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()핵심 포인트
코드에서 주목할 부분은 command=lambda:event_low(button1)처럼 lambda 함수를 사용했다는 점입니다. Tkinter의 command 옵션에는 인수를 받지 않는 함수만 직접 지정할 수 있기 때문에, lambda로 감싸주면 원하는 인수를 이벤트 핸들러에 자유롭게 전달할 수 있습니다.
실행 결과
위 코드를 실행하면 Low, Medium, High 세 개의 버튼이 포함된 창이 나타납니다. 버튼을 클릭할 때마다 클릭된 버튼에 해당하는 텍스트가 화면의 레이블에 표시됩니다.
