The following code which I use as an example, is a simple tkinter form with a label in it:
import tkinter
root=tkinter.Tk()
root.title('Form Title')
root.geometry('400x200 700 350')
def print_text(event, txt):
print(txt)
lbl1=tkinter.Label(master=root, text='Click ME!', bg='green')
lbl1.bind('<Button-1>', lambda:print_text(txt='label was clicked'))
lbl1.place(x=10, y=10)
root.mainloop()
I have a function called “print_text” that is bind to the left click event of the label. This function simply accepts a string and print it out. The “event” argument is there to account for a parameter that will be passed by tkinter, and “txt” argument is the string I want to print out. Logically what I have here makes sense (at least to me), but running this code will result in the following error:
TypeError: lambda() takes 0 positional arguments but 1 was given
I would very much appreciate it, if someone explain what is the problem here and what did I do wrong.
CodePudding user response:
you need to add the event
argument to your lambda, and pass it to print_text()
lbl1.bind('<Button-1>', lambda e:print_text(event=e, txt='label was clicked'))
CodePudding user response:
print_text
is not the callback function; it's a function used by the callback function, which you define using a lambda expression. It's the callback itself that needs to accept the argument, not necessarily print_text
.
def print_text(txt):
print(txt)
...
lbl1.bind('<Button-1>', lambda event: print_text(txt='label was clicked'))
Whether you use the event passed to the callback is up to you. For example, you can define print_text
to accept an event, and have the callback pass it explicitly.
def print_text(event, txt):
print("Got {event}")
print(txt)
lbl1.bind('<Button-1>', lambda event: print_text(event, txt='label was clicked'))