首页 > 解决方案 > 如何在单行中将函数包装在函数中以传递参数而不执行它

问题描述

假设我有一个带有 1 个参数的简单函数

 def handle_click(text):
    print(text)

我有很多按钮,每个按钮都必须传递不同的文本才能handle_click起作用

如果我将在按钮内传递一个参数,它将自动执行所有功能,例如:

Button(command=handle_click("display this"))
Button(command=handle_click("display that"))
Button(command=handle_click("show this"))
Button(command=handle_click("show that"))

但我希望在单击按钮时触发此功能

在 React.js 中,我可以使用箭头函数并这样做:

<Button onClick={() => {handleClick("show this")} }>
<Button onClick={() => {handleClick("show that")} }>
<Button onClick={() => {handleClick("so on")} }>
<Button onClick={() => {handleClick("so forth")} }>

标签: javascriptpythonreactjstkinter

解决方案


你可以这样做:

Button(command=lambda: handle_click("display this"))
Button(command=lambda: handle_click("display that"))
Button(command=lambda: handle_click("show this"))
Button(command=lambda: handle_click("show that"))

当您定义这些按钮时,它不会自动运行该函数,并且每当单击这些按钮时,该handle_click函数将使用您提供的参数运行。


推荐阅读