pythonfunctionturtle-graphicspython-turtle

Why is onclick() function calling the function inside instantly?


In this code:

button = Turtle()
button2 = Turtle()
button.hideturtle(), button2.hideturtle()

button2.color("#f73487")
button2.hideturtle()
button2.shape("square")
button2.fillcolor('#f73487')
button2.shapesize(4)
button2.penup()
button2.goto(-300, 230)
button2.write("No", align='center', font=('Arial', 12, 'bold'))
button2.setx(-300), button2.sety(182)
button2.onclick(draw_onclick2())
button2.showturtle()

button.color("#f73487")
button.hideturtle()
button.shape("square")
button.fillcolor('#f73487')
button.shapesize(4)
button.penup()
button.goto(300, 230)
button.write("Yes", align='center', font=('Arial', 12, 'bold'))
button.setx(300), button.sety(182)
button.onclick(draw_onclick())
button.showturtle()

the function button2.onclick() that contains draw_onclick2 just calls the function instantly without me clicking and I can't figure out why.

When I first tried it with the button it worked but now if I do it it just instantly calls the function.


Solution

  • button2.onclick(draw_onclick2())
                                 ^^
    

    This is actually an immediate call to the draw_onclick2 function, and the return value from it is then passed to onclick.

    What you need to do instead is pass the actual function, with something like:

    button2.onclick(draw_onclick2)
    

    You can see the effect in the following transcript:

    >>> def fn():
    ...     return 7
    ...
    
    >>> print(fn)
    <function fn at 0x7f8e36456f70>
    
    >>> print(fn())
    7
    

    You can see that fn is the function, but fn() calls the function giving its return value.