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

Jean-Michel Pichavant jeanmichel at sequans.com
Wed May 12 10:09:05 EDT 2010


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



More information about the Python-list mailing list