简体   繁体   中英

How to understand closure in a lambda?

I want to make 5 buttons in a loop, and for each buttons bind a commend to print the index. In the following solution it always prints the same index.

My code like this:

for i in range(5):
    make_button = Tkinter.Button(frame, text ="make!", 
                                 command= lambda: makeId(i))

def makeId(i):
    print(i)

It always prints 5. How can I fix this?

Resolution of variables in lambdas is done when lambda is executed. At this time, for all buttons i=5. To rectify this issue do as follows:

 make_button = Tkinter.Button(frame, text ="make!", 
                              command= lambda i=i: makeId(i))

This creates i as a local variable in a lambda. This local variable will hold correct value of i from the loop. the local variable can have any name, not necessarily i , eg command= lambda a=i: makeId(a)) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM