python - Tkinter assign button command in loop with lambda -


i'm trying create few buttons (with for) so:

def a(self, name):     print name  users = {"test":"127.0.0.0", "test2":"128.0.0.0"} row = 1 name in users:     user_button = tkinter.button(self.root,                                  text=name,                                  command=lambda: self.a(name))     user_button.grid(row = row, column = 0)     row+=1 

and buttons each own parameter (test getting test , test2 getting test2) when press buttons both print "test2" means using same function same parameter.

how can solve this?

the problem lamba in loop. lambda using name variable, name variable gets reassigned each time through loop. in end, of buttons last value name assigned in loop. avoid can use default keyword parameters in lamba expression so:

user_button = tkinter.button(self.root,                              text=name,                              command=lambda name=name: self.a(name)) 

this binds current value of name variable lamba's name keyword argument each time through loop, producing desired effect.


Comments

Popular posts from this blog

sql - can we replace full join with union of left and right join? why not? -

javascript - Parallax scrolling and fixed footer code causing width issues -

iOS: Performance of reloading UIImage(name:...) -