Passing variables to function in python -


this question has answer here:

i'm writing simple gui change brightness of monitor, i'm having problem.

def start_ui(self):     root = tk()     root.wm_title("set brightness")      col = 0     k, v in self.monitors.iteritems():         print k         scale(root, variable = doublevar(), command = lambda(r): self.change_brightness(k, r)).grid(row=0, column=col)         labelvar = stringvar()         label = label(root, textvariable=labelvar).grid(row=1, column=col)         labelvar.set(k)         col += 1      root.mainloop() 

this start ui, self.monitors dictionary looks this: {'lvds1': '1.0', 'vga1': '1.0'}.

the output of loop "lvds1, vga1" expected, however, when move sliders , callback called, last value of k passed, in case "vga1", no matter slider moved.

what causing this?

the problem lambda function - wants call change_brightness k , r, k not resolved until called. such, using value held global variable k @ time function called. if had line outside for loop said k = 'somenonsensevalue', value passed in lambda function.

try instead:

for k, v in self.monitors.iteritems():     def createlambda(k):         return lambda(r): self.change_brightness(k, r)     scale(root, variable = doublevar(), command = createlambda(k)).grid(row=0, column=col) 

this creates closure allows lambda function retain value of k @ time of creation of function.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -