简体   繁体   中英

turtle.onclick() doesn't work as supposed to

I have a script for a simple turtle race and I want the race to start when the user clicks the left-mouse-button so i have this code

def tur_race():
    for step in range(0, 135):
        tur1.forward(randint(1, 5))
        tur2.forward(randint(1, 5))


turtle.pu()
turtle.goto(-250, -150)
turtle.write("click the mouse to start")
turtle.ht()
turtle.onscreenclick(tur_race())
turtle.mainloop()

Assume that I have all variables defined.

when I run this code the race starts automatically and doesn't wait for the click.

onscreenclick takes a function as its parameter. You shouldn't be calling tur_race , turtle will do that when there is a click, rather you should pass tur_race itself. This is called a callback, you provide a function or method to be called by some event listener(eg the mouse being clicked on the screen).

In addition to @nglazerdev excellent answer, this would be your code after you apply what he said.

from turtle import *
def tur_race():
    for step in range(0, 135):
        tur1.forward(randint(1, 5))
        tur2.forward(randint(1, 5))


turtle.pu()
turtle.goto(-250, -150)
turtle.write("click the mouse to start")
turtle.ht()
turtle.onscreenclick(tur_race)
turtle.mainloop()

You take out the () in the tur_race function. Otherwise, it will be called immediately.

Hope this helps!!

You need turtle.onscreenclick( tur_race ) without () after tur_race


Python can assign function's name (without () and arguments) to variable and use it later - like in example

show = print
show("Hello World")

It can also use function's name as parameter in other function and this function will use it later.

Offen (in different programming languages) this funcion's name is called "callback"

In turtle.onscreenclick( tur_race ) you send name to function onscreenclick and turtle will use this function later - when you click screen.


If you use () in turtle.onscreenclick( tur_race() ) then you have situation

result = tur_race()
turtle.onscreenclick( result )

which doesn't work in you code but can be useful in another situations.

In addition to everyone's answer, you need to add x and y parameters in the tur_race function. This is because turtle passes x and y parameters to the function, so your code would look like:

from turtle import *
def tur_race(x, y):
    for step in range(0, 135):
        tur1.forward(randint(1, 5))
        tur2.forward(randint(1, 5))


turtle.pu()
turtle.goto(-250, -150)
turtle.write("click the mouse to start")
turtle.ht()
turtle.onscreenclick(tur_race)

turtle.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM