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()
2
  • 1
    Possible duplicate of Python Lambda in a loop Commented Sep 29, 2019 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. Commented Sep 29, 2019 at 20:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.