How to understand closure in a lambda?

前端 未结 1 1634
余生分开走
余生分开走 2020-11-22 12:46

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

相关标签:
1条回答
  • 2020-11-22 13:05

    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, e.g. command= lambda a=i: makeId(a)).

    0 讨论(0)
提交回复
热议问题