turtle.onclick() 无法正常工作

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

我有一个简单的海龟比赛脚本,我希望比赛在用户单击鼠标左键时开始,所以我有这段代码

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

假设我定义了所有变量。

当我 运行 此代码时,比赛会自动开始,不等待点击。

onscreenclick 将函数作为其参数。你不应该调用 tur_race,turtle 会在点击时调用,而你应该传递 tur_race 本身。这称为回调,您提供一个函数或方法以供某些事件侦听器调用(例如,在屏幕上单击鼠标)。

除了@nglazerdev 的出色回答外,这将是您应用他所说内容后的代码。

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

你把tur_race函数里的()去掉。否则,它将立即被调用。

希望对您有所帮助!!

你需要 turtle.onscreenclick( tur_race ) 没有 ()tur_race

之后

Python 可以将函数的名称(不带 () 和参数)分配给变量并在以后使用它 - 如示例

show = print
show("Hello World")

也可以在其他函数中使用函数名作为参数,后面这个函数会用到。

Offen(在不同的编程语言中)这个函数的名字叫做 "callback"

turtle.onscreenclick( tur_race ) 中,您将名称发送到函数 onscreenclick 并且 turtle 稍后将使用此函数 - 当您单击屏幕时。


如果您在 turtle.onscreenclick( tur_race() ) 中使用 () 那么您的情况是

result = tur_race()
turtle.onscreenclick( result )

这在您的代码中不起作用,但在其他情况下可能有用。

除了大家的回答,还需要在tur_race函数中加入x和y参数。这是因为 turtle 将 x 和 y 参数传递给函数,因此您的代码如下所示:

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