【问题标题】:turtle.onclick() doesn't work as supposed toturtle.onclick() 不能正常工作
【发布时间】:2019-04-06 13:27:23
【问题描述】:

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

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

假设我已经定义了所有变量。

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

【问题讨论】:

  • turtle.onscreenclick( tur_race )tur_race 之后没有()
  • @furas 你可以添加这个作为答案。不能吗?

标签: python turtle-graphics


【解决方案1】:

除了大家的回答,还需要在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()

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      希望这会有所帮助!

      【讨论】:

        【解决方案4】:

        tur_race 之后你需要turtle.onscreenclick( tur_race ) 而没有()


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

        show = print
        show("Hello World")
        

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

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

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


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

        result = tur_race()
        turtle.onscreenclick( result )
        

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

        【讨论】:

          猜你喜欢
          • 2013-03-30
          • 2010-11-30
          • 2021-10-02
          • 2017-08-06
          • 2013-11-22
          • 1970-01-01
          • 2013-09-10
          • 2017-04-05
          • 2013-07-25
          相关资源
          最近更新 更多