Windows 7×64 Python2.7
I’m looking to apply the Lexical closures in Python thread solution to my code. Additional readings Closures in a for loop and lexical environment
I go through a list of image, thumbnail pairs, and display the thumbnail, and upon clicking the label, it should show a new TopLevel with the full sized image in it.
What actually happens is that it is only the last image of the ImagePairs is shown. Searching around, I found that thread I posted above, but I’m uncertain about how exactly to apply it to my situation.
row, col = 0, 0
#create a frame for the row
rowFrame = Frame(master)
for image, thumb in ImagePairs:
curLbl = Label(rowFrame, image=thumb)
curLbl.grid(row=0, column=col, sticky='news')
curLbl.bind('<Button-1>', lambda e:self.popImage(image)) #or curLbl.image
col += 1
if col >= 3:
rowFrame.grid(row=row)
#create a new frame, for the next row
rowFrame = Frame(master)
col = 0
row += 1
I figured making a function like
def func(img=img):
return img
and insert it in the space between grid() and bind(), but then I get the error for a missing image. How can I modify my code to fit that in?
You can add the default value
image = imageto the lambda itself:Your idea of defining
funcwould also work if you made the default valueimageinstead ofimg:The key thing to remember is that default values are bound at the time the lambda (or function) is defined.
So each time through the loop, a new lambda is defined with its own local variable
image, with its own default value forimagebound at definition-time. Thus, when the lambda is called later, the rightimageis accessed.Contrast that with the situation when no default value is supplied:
imageis no longer a local variable of the lambda. When the lambda is called, Python goes looking for it in the enclosing scope. But by then the for-loop is done andimagein the enclosing scope is set to the last value inImagePairs.That is why you were getting the same last image no matter what button you pressed: all the lambdas were accessing the value of the same variable
image.