Search code examples
pythonuser-interfacebuttonkeyword-argument

What's the use of using a lambda function to call a function?


So, as the title suggest, I don't know what's the use of using a lambda function to call another function, especially when putting that lambda function as a keyword argument in a widget such as a button.

def multiply(x,y):
    print(x*y)

window = Tk()

x = 1
y = 1
button = Button(window, text='button' command= lambda x=x, y=y : multiply(x,y))
button.pack()

window.mainloop()

I've been trying to play with it myself. I tried not to use a lambda function to call another function but it's not working as I expected it to be.


Solution

  • What you want is that when you click on your button, your function multiply gets called with the argument "x" and "y"

    So achieve this, you need to create a pointer to the function multiply with the right argument, which you can achieve using a lambda expression.

    if you were to do button = Button(window, text='button' command= multiply(x,y))

    you are not assigning a pointer to a function to the command argument, but instead directly calling multiply(x,y)

    you can try this yourself by modify your code

    Let's see an example

    def print_value(i):
        print(i)
    
    
    lambda_list = []
    normal_list = []
    
    for i in range(0,4):
        normal_list.append(print_value(i))
    

    if you do this, you'll see that 0,1,2,3 gets printed, because I'm calling the function print_value

    Now if I do this :

    def print_value(i):
        print(i)
    
    
    lambda_list = []
    normal_list = []
    
    for i in range(0,4):
        lambda_list.append(lambda x=i : print_value(x))
    

    Nothing gets printed, because I added pointer to the function inside my list through lambda function, and not directly called the function

    but now if I continue my example by doing this

    for lambda_func in lambda_list:
        lambda_func()
    

    0,1,2,3 gets printed because I'm now calling my function pointer with the argument I gave to it (through lambda x=i)

    now last example

    If I were to do

    lambda_list = []
    
    for i in range(0,4):
        lambda_list.append(lambda: print_value(i))
    
    
    for lambda_func in lambda_list:
        lambda_func()
    

    What would be the result? answer : 3 3 3 3

    Because when you do lambda x=i : print_value(x) you are capturing the current value of " i " , but when you do lambda: print_value(i), it always references the same "i" (the one of the for loop), ence why you may need to do lambda x=x, y=y : multiply(x,y) in your case instead of lambda: multiply(x,y)

    Hope this is clear.