Search code examples
pythonmouseturtle-graphicspython-turtle

How do I turn the turtle module along with my mouse


I've been wondering how the turtle would turn with your mouse (like many io games)

Is there a command or something?


Solution

  • Here is how:

    import turtle
    
    wn = turtle.Screen() # Create screen
    t = turtle.Turtle('turtle') # Create turtle
    
    def drag(x, y): # Define drag function
        t.ondrag(0)
        t.setheading(t.towards(x, y))
        t.goto(x, y)
        t.ondrag(drag)
    
    t.ondrag(drag) # Use function on turtle
    wn.mainloop()
    

    Output:

    enter image description here

    EDIT: As pointed out by @cdlane in the comments, the 0 in the t.ondrag method should optimally be None, as the former defines a new event function that throws an exception that isn't seen as it's protected by except Exception: pass.