海龟.onclick()没有按预期工作

2024-06-24 12:08:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

假设我已经定义了所有变量。你知道吗

当我运行这个代码时,比赛会自动开始,不会等待点击。你知道吗


Tags: 代码用户in脚本fordefstep鼠标
3条回答

tur_race之后需要turtle.onscreenclick( tur_race )而不需要()


Python可以将函数名(不带()和参数)赋给变量,稍后再使用它—如示例中所示

show = print
show("Hello World")

它也可以在其他函数中使用函数名作为参数,此函数稍后将使用它。你知道吗

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

turtle.onscreenclick( tur_race )中,您将名称发送给函数onscreenclickturtle稍后将使用此函数—当您单击screen时。你知道吗


如果你在turtle.onscreenclick( tur_race() )中使用(),那么你就有了这种情况

result = tur_race()
turtle.onscreenclick( result )

这在代码中不起作用,但在其他情况下可能有用。你知道吗

除了@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函数中取出()。否则,将立即调用。你知道吗

希望这有帮助!!你知道吗

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

相关问题 更多 >