-1

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.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Luca
  • 160
  • 3
  • 14
  • 2
    Possible duplicate of [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) – Nae Jan 18 '18 at 20:52
  • 2
    Try replacing with ...`lambda t=thing: self.remove(t))`. – Nae Jan 18 '18 at 20:53

1 Answers1

2

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))
Novel
  • 13,406
  • 2
  • 25
  • 41