Jean-Michel Pichavant a écrit :
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.

[answering to the op]
The key here is that the current value of 'i' is not captured when the lambda function is created. To make it work, you'd have to capture the current value of 'i', which is usually done using a default argument ie:

for i in range(9):
    func_en.append(lambda i=i:func(i))

Now there are other solutions...


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,

done !-)

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.

FWIW, there's now (since 2.5 IIRC) a stdlib way to solve this kind of problems:

from functools import partial

def printme(x):
    print x

for i in range(9):
   Button(root, text='%d'%i, command=partial(printme,i)).pack()

HTH
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to