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

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
主站蜘蛛池模板: 铁岭市| 通海县| 偏关县| 蒲城县| 尼勒克县| 阿鲁科尔沁旗| 聊城市| 汝城县| 新昌县| 阿荣旗| 华宁县| 静安区| 定边县| 夏津县| 合阳县| 无极县| 上林县| 仁布县| 江华| 泰宁县| 乐陵市| 井研县| 辛集市| 梓潼县| 三河市| 清原| 龙井市| 大渡口区| 东乌| 泾源县| 柳河县| 铁力市| 顺义区| 扎囊县| 南川市| 常山县| 河北省| 乐东| 大厂| 望城县| 新乐市|