Tkinter Lambda Function

Using the lambda function in 'command = ' from Tkinter.

The command lambda does not take any arguments at all; furthermore there is no evt that you can catch. A lambda can refer to variables outside it; this is called a closure. Thus your button code should be:

bouton1 = Button(main_window, text="Enter",
command = lambda: get(Current_Weight, entree1))

And your get should say:

def get(loot, entree):
loot = float(entree.get())
print(loot)

What's the importance of lambda functions in tkinter?

Can anyone explain to me the importance of the lambda function when creating interface with Tkinter?

Arguably, they aren't important at all. They are just a tool, one of several that can be used when binding widgets to functions.

The problem with the binding in your question is due to the fact that when you use bind to bind an event to a function, tkinter will automatically pass an event object to that function you must define a function that accepts that object.

This is where lambda comes in. The command needs to be a callable. One form of a callable is simply a reference to a function such as the one you're using (eg: command=self.concluir_return). If you don't want to modify your function to accept the parameter you can use lambda to create an anonymous function -- a callable without a name.

So, for your specific case, you can define a lambda that accepts the argument, and then the lambda can call your function without the argument.

But all was solved when I looked into web and modified the line of code with the lambda function.

self.master.bind("<Return>", lambda event: self.concluir_return())

This works because the code is effectively the same as if you did this:

def i_dont_care_what_the_name_is(event):
self.concluir_return()
self.master.bind("<Return>", i_dont_care_what_the_name_is)

As you can see, lamda isn't required, it's just a convenient tool that lets you create a simple function on the fly that calls another function.

Understanding Python Lambda behavior with Tkinter Button

When you use () with a function name(func(args)), then it is immediately calling/invoking the function while python is executing the line, you do not want that. You want to ONLY call the function when the button is clicked. tkinter will internally call the function for you, all you have to do is give the function name.

Why use lambda? Think of it as a function that returns another function, your code can be lengthened to:

func  = lambda: comando_click("Nova_Mensagem")
botao = Button(menu_inicial, text = "Executar", command=func)

func is the function name and if you want to call it, you would say func(). And when you say command=comando_click("Nova_Mensagem") then command has the value returned by command click(because you call the function with ()), which is None and if I'm not wrong, if the given value is None, it will not be called by tkinter. Hence your function is executed just once because of () and as a result of calling the function, you are assigning the value of the function call(None) before the event loop starts processing the events.

Some other methods:

  • Using partial from functools:
from functools import partial

botao = Button(.....,command=partial(comando_click,"Nova_Mensagem"))
  • Using a helper function:
def helper(args):
def comando_click():
print(args)

return comando_click

botao = Button(...., command=helper("Nova_Mensagem"))

IMO, lambdas are the easiest way to proceed with calling a function with arguments.

Returning values in lambda function while using Tkinter button

Lambdas are just a shorthand notation, functionally not much different than an ordinary function defined using def, other than allowing only a single expression

x = lambda a, b: a + b

is really equivalent to

def x(a, b):
return a + b

In the same way, what you tried to do would be no different than doing:

def x():
a, b = read_input_data()
run(a, b)
start_button = tk.Button(text = 'Start', command = x, bg = 'firebrick', fg = 'white', font = ('helvetica', 9, 'bold'))

Lambda and threading in Python Tkinter

Thanks to @acw1668 and @Frank Yellin in the comments, I was able to fix the code.

The final code for all of this to work together is:

Button = tk.Button(root, text="Press me!", width=10, height=2, bg=YourColor, command=lambda: threading.Thread(target=sample, args=(1, 2)).start())

if the function only needs one variable, it should be:

Button = tk.Button(root, text="Press me!", width=10, height=2, bg=YourColor, command=lambda: threading.Thread(target=sample, args=(1,)).start())

Without the , the code won't work.

How to use a lambda function with an if-else statement in tkinter

The command argument requires a function with no positional arguments, so using lambda x: <do-something> will raise an error. In this case none of the arguments need to be passed during the callback and so you should simplify things to

def show_description():
key = int(code_entry.get())
if key in dictio:
textEntry.set(dictio[key])
else:
messagebox.showinfo("Info", "The number is not in the database")

show_button = Button(root, text="Mostrar descripción", command=show_description)

Also, doing this

dictio[int(code_entry.get())]

the way you did could have raised a KeyError after fixing the lambda having no arguments.

Will creating a tkinter button in a function, while using lambda as a command, function properly?

There are a couple of problems in your code.

First, your use of lambda is incorrect. When you do lambda: command, the lambda is doing nothing. If you want the lambda to call the command you need to use parenthesis to tell python to execute the function (eg: lambda: command()). However, if you're not passing any argument then the lambda itself serves no purpose. You can simply tie the command directly to the button (eg: command=command).

The other problem is that you are incorrectly defining buttons. Consider this code:

buttons = {'Quit': quit(), 'Stuff': do_something()}

The above code is functionally identical to this:

result1 = quit()
result2 = do_something()
buttons = {'Quit': result1, 'Stuff': result2}

In all cases, you need to pass a reference to a function. For example, this should work:

buttons = {'Quit': quit, 'Stuff': do_something}
...
def add_button(self, title, command, where, frame):
button = ttk.Button(frame, text=title,command=command)


Related Topics



Leave a reply



Submit