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

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
主站蜘蛛池模板: 康乐县| 宝兴县| 贵南县| 玉林市| 伊金霍洛旗| 邓州市| 嘉峪关市| 郧西县| 海盐县| 贺兰县| 新营市| 东平县| 乌兰县| 昌平区| 长兴县| 乐清市| 崇左市| 沈阳市| 榆社县| 木兰县| 施甸县| 棋牌| 新余市| 江门市| 车险| 米脂县| 微山县| 靖安县| 虹口区| 公安县| 东兴市| 华宁县| 涟源市| 永安市| 扶余县| 奎屯市| 龙海市| 新河县| 富源县| 旌德县| 环江|