Search code examples
javascriptpythonreactjstkinter

how to wrap a function inside a function in a single line to pass an arguments without executing it


assume i have a simple funtion with 1 parameter

 def handle_click(text):
    print(text)

and i have many buttons and each of them has to pass different text to handle_click function

if i will pass an argument inside the button it will automatically all the funtion like:

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

but i want this function to be triggred when the button is clicked

In React.js i could use arrow funtion and do it like:

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

Solution

  • You could do this:

    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"))
    

    It won't automatically run the function when you define these buttons, and whenever these buttons are clicked the handle_click function will run with the parameters you provided.