简体   繁体   English

为什么我的代码只打印 x 和 y 一次?

[英]Why is my code only printing x and y once?

I am trying to be able to move the turtle to my mouse click than print x and y.我试图能够将乌龟移动到我的鼠标点击而不是打印 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()

Once I run my program, it prints x and y.一旦我运行我的程序,它就会打印 x 和 y。 However, once I move the turtle with a mouse click, it does not print the coordinates.但是,一旦我用鼠标单击移动乌龟,它就不会打印坐标。

You've completely misunderstood how screen click events work in Python turtle.你已经完全误解了屏幕点击事件在 Python 海龟中是如何工作的。 When it comes to event handing, you need to review the documentation, you can't simply go by function names.当涉及到事件处理时,您需要查看文档,不能简单地通过函数名称。

You don't ask for a click, instead you register a function that will be called if/when the user clicks:您不要求单击,而是注册一个函数,如果/当用户单击时将调用该函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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