Jinsu
Jinsu

Reputation: 19

I don't know why only lambda function can run when I use GUI Button command

def btn_click(btn):
    global expression
    expression = expression + str(btn)
    btn_input.set(expression)


btn_7= Button(root, text = '7', width =5, height =2, command=lambda:btn_click(7))
# btn_7= Button(root, text = '7', width =5, height =2, command=btn_click(7))

So Can I know reason and principle about this code?

Upvotes: 0

Views: 55

Answers (2)

user14203455
user14203455

Reputation:

You may run normal functions via this 'command' argument, but the point here is that you won't be able to pass arguments to the function

def func():
    print('click')
button = Button(root, text = '7', width =5, height =2, command=func)
# If you run this and click the button you'll see 'click' message in the console

But let's say that you need to pass argument to your function, for example number of button you clicked. In this case you need to use lambda function

def func(num):
    print(num)
button = Button(root, text = '7', width =5, height =2, command=lambda: func(7))

When you do it this way happens this: When button clicked, TKinter calls this lambda function, and then lambda function calls your func() with argument '7'

Upvotes: 0

Andy
Andy

Reputation: 3170

This is common when you need to pass both a function AND its argument to something only expecting a function.

In your second example, command=btn_click(7) will call btn_click(7) and pass the results to command, which by its name is looking to take a callable (function).

If you wrap your function call in a lambda, you are then passing an unnamed callable to command which, when called, evaluates btn_click(7).

Upvotes: 1

Related Questions