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

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -