Michel Chalfoun
Michel Chalfoun

Reputation: 105

Why is text parameter responding to the loop while the command parameter is not when using the Button function in Python

I am writing a program that calculates my grades but i am stuck on a small problem that i cannot fix. I am using a for loop to append to a list multiple buttons that each follow the same method when clicked but have a different parameters each. The parameter being passed is x which is the parameter of the for loop instances. Why is x being used properly when choosing the text of the button but is being used improperly when choosing the parameter for the function?

When I run the code bellow, the buttons print out in the right order with the right text, so the x is looping and giving a different 'text' parameter (course[x].shortname) for each button. However, when i printed out the parameter of the method 'gradesCourseSelectionButtonsMethod' when it was being run, the same parameter (Number 4) was being used, instead of 0 for the first button, 1 for second, etc... 4 is the length of the list. So it is always working as if i am pressing the last button.

for x in range(0,len(course)):
    gradesCourseSelectionButttons.append(Button(
    cls. gradesCourseSelectionWindow,text= course[x].shortName, 
    relief='solid', 
    command=lambda:Course.gradesCourseSelectionButtonsMethod(x)))

i want the x to be looped in both the text parameter and the command parameter instead of just being looped through the text parameter.

Upvotes: 1

Views: 29

Answers (1)

user2314737
user2314737

Reputation: 29317

Try to assign the argument x to a local variable in the lambda function like this:

lambda y=x: Course.gradesCourseSelectionButtonsMethod(y)

Hope this helps!

Upvotes: 0

Related Questions