0

I am trying to get a button on pythons tkinter module to execute the callback function taking the variable 'name'. The problem is this code loops over to create multiple buttons. I need the variable 'name' to be assigned to the callback function at compile time rather than run time so that when any of the buttons are pressed it doesn't just execute the last instance of the variable 'name'.

The text in the button assigns at compile time, but the callback function does not assign its arguments at compile time. Does anyone know a workaround?

lbl = Button(f4, text=f'Show {name} on Map', command=lambda:callback(name),activeforeground="teal")
lbl.pack()
fennelco
  • 28
  • 4

2 Answers2

0

I would suggest doing sth. like this:

class CallbackInitiator:
    def __init__(self, name):
        self.name = name
    def __call__(self):
        callback(self.name)

And then, on button creation: command=CallbackInitiator(name). Hope that's helpful!

rizerphe
  • 1,319
  • 1
  • 13
  • 23
0

You can create functions with pre-supplied arguments using functools.partial.

In [1]: import functools

In [2]: def callback(name): 
   ...:     print(name) 
   ...:

In [3]: pre = functools.partial(callback, name='foo')
Out[3]: functools.partial(<function callback at 0x804a08d40>, name='foo')

In [4]: pre()
foo
Roland Smith
  • 39,308
  • 3
  • 57
  • 86