Home > Back-end >  Remove item from list in a for loop
Remove item from list in a for loop

Time:04-10

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.

CodePudding user response:

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.

  • Related