0

I'm creating a series of buttons in a loop with the iterator variable i. In this loop, I define a method click().

i = 0 while(i < 10): button = button() def click(): anotherMethod(i) button.onClick = click i += 1 

The problem is i seems to always be 9 (Which makes sense). I need i to "stick" to the iteration in which it was created for each method. I feel as if I'm not only missing something obvious, but I'm also asking a duplicate question. I just don't know what to search for.

3
  • 1
    button = new button() is not valid Python. Also, the code in your question causes an infinite loop. What's more, you aren't using the button variable anywhere, which makes me think that you're actually placing he button in the GUI after the loop. Commented Nov 6, 2016 at 18:45
  • 1
    you are not incrementing i either. Add i += 1 Commented Nov 6, 2016 at 18:45
  • I corrected the code, ffr. Commented Nov 6, 2016 at 19:00

1 Answer 1

2

Use a default argument in the function you're defining in your loop. The default value will preserve the value of i at the time the function is defined, even if it gets redefined later on:

for i in range(10): # do you really need to be using a while loop? def click(i=i): # use a default argument here, to save the current i value anotherMethod(i) # this refers to the argument i, not the loop variable i button.onClick = click 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! And the little block of code I put in my question was just written (admittedly poorly) to explain what I wanted. More or less pseudocode.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.