title: tkinter creating buttons in for loop passing command arguments
body: <p>I am trying to create buttons in tkinter within a <code>for</code> loop. And with each loop pass the <code>i</code> count value out as an argument in the command value. So when the function is called from the <code>command</code> value I can tell which button was pressed and act accordingly.</p>
  <p>The problem is, say the length is 3, it will create 3 buttons with titles <kbd><strong>Game 1</strong></kbd> through <kbd><strong>Game 3</strong></kbd> but when any of the buttons are pressed the printed value is always <code>2</code>, the last iteration. So it appears the buttons are being made as separate entities, but the <code>i</code> value in the command arguments seem to be all the same. Here is the code:</p>
  <pre><code>def createGameURLs(self):
      self.button = []
      for i in range(3):
          self.button.append(Button(self, text='Game '+str(i+1),
                                    command=lambda: self.open_this(i)))
          self.button[i].grid(column=4, row=i+1, sticky=W)
  
  def open_this(self, myNum):
      print(myNum)
  </code></pre>
  <p>Is there a way to get the current <code>i</code> value, each iteration, to stick with that particular button?</p>
  <hr />
  <p><sub>This problem can be considered a special case of <a href="https://stackoverflow.com/questions/3431676">Creating functions in a loop</a>. There's also <a href="https://stackoverflow.com/questions/2295290">What do lambda function closures capture?</a>, for a more technical overview.</sub></p>
  <p><sub>See also <a href="https://stackoverflow.com/questions/6920302">How to pass arguments to a Button command in Tkinter?</a> for the general problem of passing arguments to Button callbacks.</sub></p>