【问题标题】:Why is my code only printing x and y once?为什么我的代码只打印 x 和 y 一次?
【发布时间】:2020-10-22 15:56:11
【问题描述】:

我试图将海龟移动到我的鼠标点击而不是打印 x 和 y。


import turtle

tim = turtle.Turtle()
tim.shape('turtle')
screen = tim.getscreen()

def getPos():
# this should move turtle to mouse click and print coords
    screen.onscreenclick(tim.goto)
    print(tim.xcor(), tim.ycor())

def main():
# once I run, it prints coords but once I move turtle it does not
    getPos()
    screen.mainloop()
    turtle.bye()
    
main()

一旦我运行我的程序,它就会打印 x 和 y。但是,一旦我用鼠标单击移动海龟,它就不会打印坐标。

【问题讨论】:

  • 您只调用一次getPos。为什么打印会不止一次?
  • 您是否期望其他东西会调用getPos()
  • 这就是我感到困惑的原因。我的印象是 getPos() 因为 screen.mainloop() 而被多次调用。即使我只调用了一次,为什么 screen.oncscreenclick(tim.goto) 仍然有效?

标签: python turtle-graphics python-turtle


【解决方案1】:

您完全误解了屏幕点击事件在 Python turtle 中是如何工作的。在事件处理方面,您需要查看文档,不能简单地按函数名称。

您不要求单击,而是注册一个函数,如果/当用户单击时将调用该函数:

from turtle import Screen, Turtle

def gotoPos(x, y):
    tim.setheading(tim.towards(x, y))
    tim.goto(x, y)
    print(x, y)

tim = Turtle()
tim.shape('turtle')

screen = Screen()
screen.onscreenclick(gotoPos)

screen.mainloop()

【讨论】:

  • 好吧,这更有意义。非常感谢。我对 Turtle 很陌生,所以在阅读文档时我很困惑。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 2014-03-17
  • 1970-01-01
  • 2013-08-20
  • 2015-12-17
相关资源
最近更新 更多