Changing global variables in tkinter/pmw callback
Carey Evans
careye at spamcop.net
Fri Apr 6 21:44:24 EDT 2001
Brian Elmegaard <be at mek.dtu.dk> writes:
> I never found out how to pass arguments to a tkinter callback without
> using a lambda.
Usually you pass a bound method, or an instance of a class with a
__call__ method. For the latter, my brother uses something like this:
class Command:
def __init__(self, func, *args, **kw):
self.func = func
self.args = args
self.kw = kw
def __call__(self, *args, *kw):
args = self.args + args
kw.update(self.kw)
self.func(*args, **kw)
So if you have a function "on_click" that you want to pass a
particular variable to, you do something like:
def on_click(source, counter=None, button=None):
print "%s from %s clicked." % (button, source)
counter[0] += 1
def setup():
button = Button()
count = [0]
button.configure(command=Command(on_click, 'setup', counter=count))
A more Pythonic way would be to use a separate class, and pass a bound
method:
class ButtonClicker:
def __init__(self, source, button):
self.source = source
self.button = button
self.count = 0
def on_click(self):
print "%s from %s clicked." % (self.button, self.source)
self.count += 1
def setup():
button = Button()
clicker = ButtonClicker('setup', button)
button.configure(commmand=clicker.on_click)
--
Carey Evans http://home.clear.net.nz/pages/c.evans/
"Quiet, you'll miss the humorous conclusion."
More information about the Python-list
mailing list