lambda i=i: not giving result for button in loop

Question:

I’m new to coding and tkinter and after looking for solution to create button in a loop I ended on this solution:

while x <= 10:
    btn = Button(text=x).grid(row=1, column=1)
    window.bind('<Button-1>', lambda x=x: print(x))

But this solution return:

<ButtonPress event state=Mod1 num=1 x=57 y=12>

and not the value of x.

What would be a solution for that?

Asked By: Vincent Dorion

||

Answers:

When you bind a function to an event, that function will be called with a parameter. This parameter is an object representing the event.

In your case you’re binding to an anonymous function that accepts one argument named x. Thus, when the function is called, even though you’ve initialized x to an integer, x will be set to this event object.

The solution is that your lambda needs to accept this event along with the parameter x so that x doesn’t get overwritten.

window.bind('<Button-1>', lambda event, x=x: print(x))

However, the code snippet you provided doesn’t define x (ie: x isn’t a loop variable and you don’t do x=... anywhere) so I’m not sure if that’s quite right. If you want x to be the loop variable then it needs to be x=i:

window.bind('<Button-1>', lambda event, x=i: print(x))
Answered By: Bryan Oakley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.