Issue with button command on Tkinter

Question:

Code

from tkinter import *

class Thing:

    var = {}
    def item(self):
        self.root = Tk()
        # Settings of main window
        things = [] # Array which contains items with different values
        for thing in things:
            # 1*
            self.var[f'b{thing}'] = Button(self.root, text='Test',command = lambda: self.remove(thing))
            self.var[f'b{thing}'].pack()

    def remove(self, thing=None):
        print(thing)
        # 2*
Thing().item()

Question

When I press for the first time any button, the class remove print the correct value, when I try to press another button, the class ‘remove’ print another time the first value instead of second.
I’m thinking that the issue is in buttons command.
I appreciate every kind of help, thanks in advance.

Asked By: Luca

||

Answers:

You can’t use lambda in a loop like that. You will have to use functools.partial.

from functools import partial
#...
self.var[f'b{thing}'] = Button(self.root, text='Test',command = partial(self.remove, thing))
Answered By: Novel
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.