1

I am trying to make a software but the problem is when I click the button in below code it always shows 9 as output. can anyone suggest solution for this.

from tkinter import *

root = Tk()

frame = Frame(root)

def click(i):
  print(i)

for i in range(10):
    btn = Button(frame,text="Button",command=lambda: click(i))
    btn.pack(...)

root.mainloop()    
soham
  • 28
  • 4
  • 1
    Does this answer your question? [tkinter creating buttons in for loop passing command arguments](https://stackoverflow.com/questions/10865116/tkinter-creating-buttons-in-for-loop-passing-command-arguments) – acw1668 Jan 13 '21 at 08:39

1 Answers1

1

You need to use a partial object:

from functools import partial

for i in range(10):
    btn = Button(frame,text="Button",command=partial(click, i))

Or a lambda function default value:

for i in range(10):
    btn = Button(frame,text="Button",command=lambda i=i: click(i))
Novel
  • 13,406
  • 2
  • 25
  • 41
  • This is the correct answer, but I think the OP needs to know why his "obvious" bindings don't work as expected. I don't have the link right now though. – RufusVS Jan 13 '21 at 07:17