PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

[FIXED] What does lambda event: do?

 November 05, 2022     lambda, python, tkinter     No comments   

Issue

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!


Solution

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.



Answered By - M. Chak
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing