Turtle in python- Trying to get the turtle to move to the mouse click position and print its coordinates

前端 未结 1 891
难免孤独
难免孤独 2020-12-04 02:32

I\'m trying to get the mouse position through Python turtle. Everything works except that I cannot get the turtle to jump to the position of the mouse click.



        
相关标签:
1条回答
  • 2020-12-04 03:01

    You are looking for onscreenclick(). It is a method of TurtleScreen. The onclick() method of a Turtle refers to mouse clicks on the turtle itself. Confusingly, the onclick() method of TurtleScreen is the same thing as its onscreenclick() method.

    24.5.4.3. Using screen events¶

    turtle.onclick(fun, btn=1, add=None)
    turtle.onscreenclick(fun, btn=1, add=None

    Parameters:

    • fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas
    • num – number of the mouse-button, defaults to 1 (left mouse button)
    • addTrue or False – if True, a new binding will be added, otherwise it will replace a former binding

    Bind fun to mouse-click events on this screen. If fun is None, existing bindings are removed.

    Example for a TurtleScreen instance named screen and a Turtle instance named turtle:

    >>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
    >>>                             # make the turtle move to the clicked point.
    >>> screen.onclick(None)        # remove event binding again
    

    Note: This TurtleScreen method is available as a global function only under the name onscreenclick. The global function onclick is another one derived from the Turtle method onclick.

    Cutting to the quick...

    So, just invoke the method of screen and not turtle. It is as simple as changing it to:

    screen.onscreenclick(turtle.goto)
    

    If you had typed turtle.onclick(lambda x, y: fd(100)) (or something like that) you would probably have seen the turtle move forward when you clicked on it. With goto as the fun argument, you would see the turtle go to... its own location.

    Printing every time you move

    If you want to print every time you move, you should define your own function which will do that as well as tell the turtle to go somewhere. I think this will work because turtle is a singleton.

    def gotoandprint(x, y):
        gotoresult = turtle.goto(x, y)
        print(turtle.xcor(), turtle.ycor())
        return gotoresult
    
    screen.onscreenclick(gotoandprint)
    

    If turtle.goto() returns None (I wouldn't know), then you can actually do this:

    screen.onscreenclick(lambda x, y: turtle.goto(x, y) or print(turtle.xcor(), turtle.ycor())
    

    Let me know if this works. I don't have tk on my computer so I can't test this.

    0 讨论(0)
提交回复
热议问题