-2

I am practicing tkinter, and i'm stuck with a problem.

i need to make a few buttons inside a for loop, and give it a command based on the iteration of the loop.

but no matter what button i press, the output is always 'd'. this is a simplified version:

from tkinter import *

root = Tk()

def write(n):
    print(n)

indexes = ['a','b','c','d']

for i in range(len(indexes)):
    button = Button(root, text=indexes[i], command=lambda:write(indexes[i]))
    button.grid(row=0, column=i)

root.mainloop()

does anybody know what to do? thanks

syter
  • 135
  • 2
  • 10

1 Answers1

2

Try this code:

from tkinter import *

root = Tk()

def write(n):
    print(n)

indexes = ['a','b','c','d']

for i in range(len(indexes)):
    button = Button(root, text=indexes[i], command = lambda i=i:write(indexes[i]))
    button.grid(row=0, column=i)

root.mainloop()
Eduards
  • 1,734
  • 2
  • 12
  • 37