0

I really don't understand this.. The text of y is fine but when it is passed into the lambda function to print y it just prints 2.

It seems simple yet I don't get it.

Could someone explain or tell me how I can fix this?

Thanks

from tkinter import *

window = Tk()

buttonHeight = 10
buttonWidth = 25

gridItemsList = [['-', '-', '-'], ['-', '-', '-'],['-', '-', '-']]
for y in range (0, 3):
    for x in range(0, 3):           
            gridItemsList[2-y][x] = ([Button(window, height=buttonHeight, width=buttonWidth, background="white", text=y, command=lambda:print(y)), [] ])
            gridItemsList[2-y][x][0].grid(column = y, row=x, padx=20, pady=20)

mainloop()
  • 1
    Possible duplicate of [Python Lambda in a loop](https://stackoverflow.com/questions/19837486/python-lambda-in-a-loop) – Olvin Roght Sep 29 '19 at 19:55
  • it doesn't copy value from `y` when you create button. All buttons keep only reference to variable `y` and get value from `y` when you press button - and when you press button then `y` has last value from `for`-loop. Using `command=lambda a=y:print(a)` it copies value from `y` when you create button so every button has different value. – furas Sep 29 '19 at 20:05

1 Answers1

1
 y in range(0,3) 

gives

 y=0, y=1, y=2

Hence when your widgets are being created the value of y is changing via the loop(0,1,2), hence the button text are OK. but at the end of the loop, the value of y is y=2.

Hence, you will always get 2 as the output of your print functions because the buttons are only available to use after the loop is done and the last value and current value of y is 2 after the loop.

Samuel Kazeem
  • 787
  • 1
  • 8
  • 15