0

I was trying to use the GUI Buttons in Tkinter and ran into a problem when trying to use them. This code should (at least I expected it to) generate a few buttons, that, when clicked, print out the letter that is showing. However, no matter which button is pressed, it always prints out the last-generated button's result. Is there a different way I should be using functions like this?

import tkinter  

win = tkinter.Tk()
players = ["A","B","C","D"]

for p in players:
    playerBtn = tkinter.Button(win,text=p,command=lambda : print(p))
    playerBtn.pack()

tkinter.mainloop()
Nick S
  • 1

1 Answers1

1

That is happening because lambda is just looking up the global value of p. To change that we will do the following -

import tkinter  

win = tkinter.Tk()
players = ["A","B","C","D"]

for p in players:
    player_button = tkinter.Button(win, text=p, command=lambda button_text=p: print(button_text))
    player_button.pack()

tkinter.mainloop()

Tested this on Ubuntu 18.04 and it works just like you want.

You can refer to this SO post for more details about this behavior.

jar
  • 2,646
  • 1
  • 22
  • 47