Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove item from list in a for loop

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading