Tkinter Creating multiple buttons with a "different" command function

First of all, sorry for the title, I could not find a better one.

The following code is a minimalized version of the problem that I have in my Python program (I'm new, by the way).

def onClick(i):
    print "This is Button: " + str(i)
    return

def start():
    b = [0 for x in range(5)]
    win = Tkinter.Tk()
    for i in range(5):
        b[i] = Tkinter.Button(win,height=10,width=100,command=lambda : onClick(i))
        b[i].pack()
    return

What he does: Any button that I click says: "This is a button: 4".

What I want: The first button should say "This is the button: 0", etc.

Is this the desired behavior of Python? And if so, why? How can i fix this?

On the other hand, this works great:

def start():        
    x = [0 for x in range(5)]
    for i in range(5):
        x[i] = lambda:onClick(i)
        x[i]()
    return
+4
source share
1 answer

, ( i -, ):

def start():
    buttons = []
    win = Tkinter.Tk()
    for i in range(5):
        b = Tkinter.Button(win, height=10, width=100, command=lambda i=i: onClick(i))
        b.pack()
        buttons.append(b)
+3

All Articles