0

I'm making simple UI in Python using , in which I have 5 similar buttons with different labels on. To make code a little shorter I created buttons in loop like this:


self.btntext = ["-10mm", "-1mm", "Stop", "+1mm", "+10mm"]

self.ctrButtons = []
    for i in self.btntext:
        self.ctrButtons.append(tk.Button(self.buttonFrame, text=i, command= lambda: self.addSubtract(i)))

I thought that it would pass current button text to addSubtract function but instead it always passes the last element of btntext.

Why it works like this? And can I make this work without adding 5 buttons individually?

0

1 Answer 1

1

You almost had it. Your lambda is missing a portion that is required to deal with this very problem:

Change this:

lambda: self.addSubtract(i)

To this:

lambda x=i: self.addSubtract(x)

The reason we need to do this is due to how lambdas are executed. This function does not evaluate the assigned variable until it is called.

To deal with this we force it to evaluate the variable by assigning it to another variable within the lambda as we create them.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.