Monday, April 21, 2025

Python Turtle - Drag Turtle with Mouse

Dragging turtle is more work than pointing turtle. We need to use new method ondrag() and pass to it same method again to try to get to new position.

This will work partially, but it's still something. At some point, app will break:

from turtle import *

t = Turtle()
t.shape("turtle")
t.shapesize(10, 10, 10)

t.speed(0)
t.color("red")

def get_coords(x, y):
    t.setheading(t.towards(x, y))
    t.goto(x, y)
    t.ondrag(get_coords)

onscreenclick(get_coords)

To solve problem when application break, we must update our custom function by adding this line as first one:

t.ondrag(None)

So full working script is this one:

from turtle import *

t = Turtle()
t.shape("turtle")
t.shapesize(5, 5, 5)

t.color("red")

def get_coords(x, y):
    t.ondrag(None)
    t.setheading(t.towards(x, y))
    t.goto(x, y)
    t.ondrag(get_coords)

onscreenclick(get_coords)

You are strongly advised to check corresponding YouTube tutorial on How to Drag Turtle with Mouse.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...