Python 3.0 using turtle.onclick

不羁岁月 提交于 2019-11-28 02:22:21

You need to use the Screen class. However, if you want to stay away from OOP, you can use the built-in method turtle.onscreenclick(func).

Replace

def main():
    t.onclick(getPos)
    t.mainloop()
main()

with

def main():
    t.onscreenclick(getPos)
    t.mainloop()
main()

Awesome job figuring out a solution on your own.

Did you ever look through the docs for turtle?

http://docs.python.org/2/library/turtle.html

Looks like you can import screen as well as turtle from the module. screen has an onclick event of its own that does what you expect it to.

Note the following line on how to get access to the screen object:

The function Screen() returns a singleton object of a TurtleScreen subclass.
This function should be used when turtle is used as a standalone tool for
doing graphics. As a singleton object, inheriting from its class is not
possible.

Disclaimer: I've never used turtle before.

Alright, I figured out a work around. Its not a perfect solution but it works pretty well. Because onclick will only respond if you click on the arrow head, I made the arrow head encompass the entire screen. Then I hid it. What you need to do is hover over the position you want to go to, press "a" and when it goes black click the screen. The shell will then display the coordinates you need. Make sure you always go back to (1000,0).

import turtle as t

def showTurtle():
    t.st()
    return

def getPos(x,y):
    print("(", x, "," ,y,")")
    return

def hideTurtle(x,y):
    t.ht()
    return

def main():
    t.speed(20)
    t.shapesize(1000,1000)
    t.up()
    t.goto(1000,0)
    t.ht()
    t.onkey(showTurtle,"a")
    t.listen()
    t.onclick(getPos)
    t.onrelease(hideTurtle)
    t.mainloop()
main()

Also, in case anyone from my class finds this, I am a CS student in binghamton and if you use this I recommend leaving no trace. The prof has seen this and will recognize it.

You have to get first the screen object the turtle is drawing on and then call onclick() of the screen object. Here is an example:

import turtle as t

def getPos(x,y):
    print("(", x, "," ,y,")")
    return

def main():
    s = t.getscreen()
    s.onclick(getPos)
    t.mainloop()

main()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!