How to add callbacks that is the same function with different argument in Tkinter python26?

Dave Angel davea at ieee.org
Wed May 12 11:09:45 EDT 2010


Jean-Michel Pichavant wrote:
> chen zeguang wrote:
>> code is in the end.
>> I want to print different number when pressing different button.
>> Yet the program outputs 8 no matter which button is pressed.
>> I guess it's because the callback function is not established untill 
>> the button is pressed, and i has already reached to 8.
>>
>> then How to add callbacks that is the same function with different 
>> argument?
>>
>> CODE:
>> from Tkinter import *
>> root = Tk()
>> def func(x):
>>     print x
>>     return
>>
>> func_en=[]
>> for i in range(9):
>>     func_en.append(lambda:func(i))
>> for i in range(9):
>>     func_en[i]()
>> for i in range(9):
>>     Button(root, text='%d'%i, command=func_en[i]).pack()
> from Tkinter import *
> root = Tk()
>
> def func(x):
>    def _printme():
>        print x
>    return _printme
>
> for i in range(9):
>    Button(root, text='%d'%i, command=func(i)).pack()
>
> Surely someone will explain why your code was not working, I can't 
> 'cause I don't use lambda, it brings more problems than it solves 
> (maybe I'm not talented enough).
> Above is how I would have written the code, I tested it, looks like 
> it's working.
>
> JM
This solution works because of the nested function.  Chen could do the 
same with nested lambdas, or by using default arguments in the lambda.

The trick is just that you need separate instances of x for each 
callback, so they don't all get incremented in the loop.

DaveA



More information about the Python-list mailing list