Reputation: 3
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()
Upvotes: 0
Views: 77
Reputation: 805
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.
Upvotes: 1