What is the difference between lambda:
and lambda event:
. I did some research but can still not work out the difference.
Consider this code:
import tkinter as tk
root = tk.Tk()
r = 0
def func(n):
r = n
#works
b1 = tk.Button(root, text='1')
b1.bind('<Button-1>', lambda event: func(1))
b1.pack()
#does not work
b2 = tk.Button(root, text='2')
b2.bind('<Button-1>', lambda: func(2))
b2.pack()
tk.mainloop()
Why does button 2 work but not button 1? Specifically, I get this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/tkinter/__init__.py", line 1921, in __call__
return self.func(*args)
TypeError: <lambda>() takes 0 positional arguments but 1 was given
Thanks!
CodePudding user response:
Event is an argument to the lambda function. In other words, if you define
x = lambda a: a 10
You can run x(10)
to get 20
.
You can’t, on the other hand, do
x = lambda: 10
x(10)
As that lambda function takes no arguments
Your error happens because tkinter tried to pass a positional argument to a lambda function that doesn’t take any.