[Tkinter-discuss] No Parameters fo Callback functions?
Fredrik Lundh
fredrik at pythonware.com
Fri Nov 4 10:28:27 CET 2005
Martin Franklin wrote:
> The 'standard alternative' to lambda is to use a callback class
> like so :)
>
> class Callback:
> def __init__(self, checkbutton, action):
> self.checkbutton = checkbutton
> self.action = action
>
> def __call__(self):
> self.action(self.checkbutton)
I strongly recommend using local function objects instead; the code
is straightforward, they're cheap to create, and they give you a lot
more flexibility the day you need to add more functionality to your
callbacks.
def callback():
self.actionFunction("checkButton1")
cb1 = Checkbutton(self, command=callback)
def callback():
self.actionFunction("checkButton2")
cb2 = Checkbutton(self, command=callback)
or, in a loop
# create ten buttons
for i in range(10):
def callback(i=i): # <-- note: bind to value, not name
self.actionFunction("checkButton%d" % i)
cb = Checkbutton(self, text="Button %d" % i, command=callback)
cb.pack()
(the i=i construct is used to bind to the *current* value of the i
variable, rather than whatever value it has when you leave the
current scope)
</F>
More information about the Tkinter-discuss
mailing list