官术网_书友最值得收藏!

Passing arguments to callbacks

If a callback does not take any argument, it can be handled with a simple function, such as the one shown in the preceding code. However, if a callback needs to take arguments, we can use the lambda function, as shown in the following code snippet:

def my_callback (argument)
#do something with argument

Then, somewhere else in the code, we define a button with a command callback that takes some arguments, as follows:

tk.Button(root,text="Click", command=lambda: my_callback ('some argument'))

Python borrows a specific syntax from functional programming, called the lambda function.  The lambda function lets you define a single-line, nameless function on the fly. 

The format for using lambda is as follows:

lambda arg: #do something with arg in a single line

Here's an example:

square = lambda x: x**2

Now, we can call the square method, as follows:

>> print(square(5)) ## prints 25 to the console
主站蜘蛛池模板: 萨迦县| 呼图壁县| 时尚| 精河县| 宁阳县| 平邑县| 正宁县| 芜湖县| 临猗县| 连州市| 阿鲁科尔沁旗| 浙江省| 边坝县| 云梦县| 南城县| 商城县| 河东区| 建德市| 林甸县| 宜丰县| 铜陵市| 建宁县| 荆州市| 灵山县| 禄丰县| 清水县| 梁河县| 雷州市| 老河口市| 安丘市| 正阳县| 保靖县| 桑植县| 丹寨县| 丰都县| 巨鹿县| 明星| 富蕴县| 屏山县| 无棣县| 恭城|