0

I am a beginner in python, I used tkinter to build a to-do list program. But the problem is I don't understand how it works.

from tkinter import *

root = Tk()

def insert_Task(name):
    name = Checkbutton(root, text=name, command= lambda: del_task(name))
    name.pack()
    
def del_task(name):
    name.destroy()
    
insert_Entry = Entry(root)
insert_Button = Button(root, text="Ok", command=lambda: insert_Task(insert_Entry.get()))

insert_Entry.pack()
insert_Button.pack()

root.mainloop()

The only way this should work is when name is passed into text, it is insert_Entry.get() and when the function is called it is the Checkbutton object.

Can someone explain to me if this is the case?

bababooey2
  • 33
  • 1
  • 4

1 Answers1

0

lambdas are used to create anonymous functions. The code:

command=lambda: insert_Task(insert_Entry.get())

Can also be written as:

def click_next(): #=== any name
    insert_Task(insert_Entry.get())

insert_Button=Button(....,command = click_next)

Why do we use lambda to pass arguments?
We need to pass the reference of the function, i.e without providing a (). Or else, the function is executed right away and the returned value is set as the command.

When you click on the button, insert_Entry.get() returns all the text which is entered in insert_Entry. This is passed as the argument in insert_Task where a Check button is created with that name.

Similarly:

name = Checkbutton(root, text=name, command= lambda: del_task(name))

in this, a reference of the Checkbutton is passed as an argument to del_task so that on clicking on it, the method in invoked and the selected check button is destroyed

  • So, basically when lambda are used, the argument inside del_task function is referring to the Checkbox itself and when lambda is not used it is referring to the value inside of insert_Entry. – bababooey2 Aug 27 '21 at 12:34