I am storing a matrix of Entries, each attached to a unique StringVar
. On the callback for the StringVar
, I want to be able to find which StringVar
it was, with respect to the matrix. This is what I have:
def callback(sv, index):
print index
for i in range(ncols):
for j in range(self.nrows):
sv = StringVar()
uniqueId = str(i)+str(j)
sv.trace("w", lambda name, index, mode, sv=sv: callback(sv, uniqueId))
self.results[i][j] = Entry(gridtable,textvariable=sv,bg='grey',borderwidth=1,fg='black',width=self.widget_width).grid(row=j+2,column=i+1,sticky='ew')
However, it always prints the same index ('718' - which is '7'+'18': the values that i and j stop at). How can I get a unique identifier for these StringVars
?
The sv
variable is changing in your code, but uniqueID
is getting stuck at the last value it's given. You can set it to remember its value on that iteration of the loop by including it in the lambda expression, like this:
from Tkinter import *
def callback(var, index):
print var, index
root = Tk()
for i in range(10):
var = StringVar()
uniqueID = i
var.trace('w', lambda name,index,mode, var=var, uniqueID=uniqueID: callback(var, uniqueID))
Entry(root, textvariable=var).pack()
mainloop()