-2

I've writen this code. I Want it to print the label's text near each button when I press the button. For example when I press second button it must print 'label 2'. But it always prints last label, 'label 20'.

from tkinter import *
from tkinter import ttk

root = Tk()
for index,i in enumerate(range(0,20)):
    label = ttk.Label(root, text='line {}'.format(i+1))
    label.grid(row=index, column=0)
    button = ttk.Button(root, text='show info', command=lambda: print(label['text']))
    button.grid(row=index, column=1)

root.mainloop()

How can I fix it?

Thanks

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
myregm
  • 67
  • 1
  • 8
  • Or this one. [Python tkinter creating buttons in for loop passing command arguments](https://stackoverflow.com/questions/10865116/python-tkinter-creating-buttons-in-for-loop-passing-command-arguments) – Lafexlos Oct 18 '17 at 07:32

1 Answers1

0

There is only a single outer scope for lambda function defined in loop. Hence all lambda instances refer to the last value of the variable in the scope. It can be resolved by binding the current value as a parameter to the lambda (which introduces lambda level scope!) and hence each lambda gets a different input,

from tkinter import *
from tkinter import ttk

root = Tk()
for index,i in enumerate(range(0,20)):
    label = ttk.Label(root, text='line {}'.format(i+1))
    label.grid(row=index, column=0)
    button = ttk.Button(root, text='show info', command=lambda lb=label: print(lb['text']))
    button.grid(row=index, column=1)

root.mainloop()
Jayson Chacko
  • 2,388
  • 1
  • 11
  • 16