0

I have a for loop in my tkinter window that creates a label and a button for every item of a list. I want the button of a corresponding list-item to remove the item from the list, but no matter what button i click, the last element always gets removed! Can someone please help?

My code:

import tkinter
import ntkutils

list = [1, 2, 3, 4, 5, 6]
root = tkinter.Tk()

def refresh():
    y = 40

    def pressed(i):
        list.remove(i)
        ntkutils.clearwin(root)
        refresh()

    for index in list:
        tkinter.Label(text=index).place(x=40, y=y)
        tkinter.Button(text="-", command=lambda:pressed(index)).place(x=100, y=y)
        y = y+20

refresh()
root.mainloop()

PS: ntkutils.clearwin just removes all of the window`s content.

nef2008
  • 3
  • 3

1 Answers1

0

Change your lambda expression as per below.

tkinter.Button(text="-", command=lambda x=index:pressed(x)).place(x=100, y=y)

This will use the value of the for loop rather than always the last value. A strange quirk of lambdas.

scotty3785
  • 6,763
  • 1
  • 25
  • 35
  • I don't think it should be considered a quirk of using `lambda`. You would observe the same behaviour even if you define a function inside the loop and use that function in place of lambda. I have explained that in [this](https://stackoverflow.com/questions/71798866/on-clicking-the-numbers-to-input-it-onto-the-entry-widget-it-always-adds-10-rat/71799742#71799742) answer. – Sriram Srinivasan Apr 09 '22 at 17:33
  • @SriramSrinivasan Ok. Not a quirk then. A commonly misunderstanding of how lambdas work. – scotty3785 Apr 09 '22 at 17:35