Wednesday, June 16, 2010

[Py] Use lambda expression for callback functions of widgets

Let's see a quotation about Tkinter callbacks:
A common beginner’s mistake is to call the callback function when constructing the widget. That is, instead of giving just the function’s name (e.g. “callback”), the programmer adds parentheses and argument values to the function
That's true. I just solved one problem of this kind in my code.

In short, we cannot use callbacks of widgets in the form of
Widget(text="some text", command=callback(argv)).pack()

The reason has been stated clearly in the first link of this post. To call the callbacks which have arguments, we need to utilize the lambda expression.

I have tried with 3 test programs. They are listed as follows.

1. from Tkinter import *
2.
3. def cb_test(i):
4. print i
5.
6. root = Tk()
7.
8. for i in range(5):
9. Button(root, text=str(i), command=cb_test(i)).pack() # test 1
9. Button(root, text=str(i), command=lambda:cb_test(i)).pack() # test 2
9. Button(root, text=str(i), command=lambda x=i:cb_test(x)).pack() # test 3
10. Button(root, text="Quit", command=root.quit).pack()
11.
12. root.mainloop()

If you would like to try with my codes, please note there are 3 lines denoted as line 9. Keep only one of them and delete the other two.

No comments:

Post a Comment