python - Checkbuttons and buttons: using lambda -


i trying make number of checkboxes based on list, looks if screwing command call , variable aspect of button.

my code is:

class example(frame):  def __init__(self, parent):     frame.__init__(self, parent)      self.parent = parent     self.initui()  def initui(self):      self.courses = ["cse 4444", "cse 4343"]     self.vars = []      self.parent.title("homework helper")      self.course_buttons()      self.pack(fill=both, expand=1)  def course_buttons(self):     x = 0     y = 0      in range(0, len(self.courses)):         self.vars.append(intvar())         cb = checkbutton(self, text=self.courses[i],                          variable=self.vars[i],                          command=lambda: self.onclick(i))         cb.select()         cb.grid(column=x, row=y)         y = y+1  def onclick(self, place):      print place     if self.vars[place].get() == 1:         print self.courses[place] 

the test far course printed on console when check box on, works second button, button "cse 4343". when interact button "cse 4444", nothing printed.

also, "place" value onclick 1, whether clicking button "cse 4343" or button "cse 4444".

when make lambda function, references resolve values when function called. so, if create lambda functions in loop mutating value (i in code), each function gets same i - last 1 available.

however, when define function default parameter, reference resolved function defined. adding such parameter lambda functions, can ensure value intended them to.

lambda i=i: self.onclick(i) 

this referred lexical scoping or closure, if you'd more research.


Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -