[tkinter] command in button

ivor·2022년 11월 10일
0

App

목록 보기
3/3

(tkinter) 'Button' command에는 무엇을 전달해야 할까?

from tkinter import *

def say():
    print("hello")

root = Tk()

btn = Button(root, text="say hello", command=say)
btn.pack()

root.mainloop()

tkinter를 이용해 GUI 프로그램을 만들 때 Button을 보통 위와 같은 형태로 만든다.
command에는 메서드, 함수가 전해지는데 이때 parameters를 갖는 함수를 만들어 arguments를 전달할 순 없을지 궁금해졌다.

https://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter

찾아보니 이러한 의문을 갖는 사람이 있었고 답변을 바탕으로 해결할 수 있었다.

문제를 정확히 인식하기 위해 다음과 같은 두가지 코드를 비교했다.

from tkinter import *

def say(string):
    print(string)

root = Tk()

btn = Button(root, text="say hello", command=say("hello"))
btn.pack()

root.mainloop()
from tkinter import *

def say(string):
    print(string)

root = Tk()

btn = Button(root, text="say hello", command=lambda: say("hello"))
btn.pack()

root.mainloop()

첫번째 코드는 버튼을 눌러도 "hello"라는 문자열이 print되지 않는다. 두번째 코드는 의도대로 버튼을 누를 때마다 "hello"라는 문자열이 print 된다.
차이는 lambda를 쓰냐 안 쓰냐인데 lambda : say("hello")를 통해 command에 새로운 익명함수가 들어간다고 생각했다. 즉 command에 전달될 수 있는 '함수'라는 조건을 lambda를 통해 만족시킨다고 생각했다. (좀 더 공부해봐야겠다)

다음과 같은 함수가 있다고 했을 때

def abc(num):
	return num

abc(7)lambda : abc(7)의 차이를 생각하면 될 것 같다.
abc(7)는 함수의 결과로 나온 어떠한 '값'이고 lambda : abc(7)abc(7)의 동작을 내부에 포함하는 어떠한 '함수'라고 생각했다.

위의 예시인 say("hello"), lambda : say("hello")도 마찬가지로 함수의 '동작'과 어떤 '함수'라고 보면 되지 않을까.


REF

https://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter

https://076923.github.io/posts/Python-tkinter-3/

profile
BEST? BETTER!

0개의 댓글