[Python] Understanding Python Lambda behavior with Tkinter Button [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 5, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to understand how a button is working using lambda. I have the following Python code:

    from tkinter import *

    def comando_click(mensagem):
    print(mensagem)

    menu_inicial = Tk()
    menu_inicial.geometry("500x250+200+200")

    botao = Button(menu_inicial, text = "Executar", command=comando_click("Nova_Mensagem"))
    botao.pack()

    menu_inicial.mainloop()


    But my button doesn't work when I click on it, it only shows the print once in the console when I run the code, I added some prints here in the question:

    Problem Picture one

    Well it seems that when I use the Lambda function in the button it works and I really would like to know why.

    Lambda working button Picture one

    I just added to the button the lambda :

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


    Lambda working button Picture two

    Why with lambda it works? Shouldn't it work without lambda too since lambda is basically a anonymous function?

    Continue reading...

Compartilhe esta Página