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

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
主站蜘蛛池模板: 双流县| 嵊州市| 丰镇市| 靖江市| 玛沁县| 商丘市| 佛学| 新安县| 洛南县| 开江县| 台南县| 海兴县| 漳浦县| 信宜市| 阿图什市| 旌德县| 手游| 赤壁市| 商南县| 竹溪县| 沈丘县| 武夷山市| 漳州市| 穆棱市| 齐齐哈尔市| 襄城县| 宿州市| 廊坊市| 马龙县| 东山县| 深泽县| 三原县| 平度市| 连云港市| 方正县| 石景山区| 前郭尔| 澜沧| 全椒县| 葵青区| 如东县|