Whenever I dynamically create buttons in tkinter through a loop, to call a function with a value assigned to them through the loop, like so:
from tkinter import *
root=Tk()
def add(text):
print(text)
for i in ('a', 'b', 'c'):
Button(root, text=i, command=lambda:add(i)).pack()
mainloop()
I always have the problem that the function is called with the last value in the loop, whatever button I press. In this case, it simply prints c
whatever button I press. I do not know if this is a problem with lambda
or tkinter
, or simply my programming, but I would like to know how to fix it.
I have tried using copy.copy
, copy.deepcopy
(on the lambda
function and the string), and [:]
and str
(on the string).