Tech With Tim Logo
Go back

Drawing With Mouse

Mouse Events Continued

In the last tutorial I explained how to check to see if the mouse was being clicked. In this tutorial I will show how to track the position of the mouse and use it to draw lines and shapes similarly to a paint program.

Up until this point we have only been using a turtle object from the turtle module. However, for this tutorial we will have to use another object called screen.

import turtle
from turtle import Turtle
from turtle import Screen

screen = Screen()
t = Turtle("turtle")

We now need to create two functions that will be used to clear the screen and move the turtle.

def dragging(x, y):  # These parameters will be the mouse position
    t.ondrag(None)
    t.setheading(t.towards(x, y))
    t.goto(x, y)
    t.ondrag(dragging)

def clickRight():
    t.clear()

Now we will setup the function main which will run our program.

def main():  # This will run the program
    turtle.listen()
    
    t.ondrag(dragging)  # When we drag the turtle object call dragging
    turtle.onscreenclick(clickRight, 3)

    screen.mainloop()  # This will continue running main() 

Bringing it all together we get the following.

import turtle
from turtle import Screen, Turtle

screen = Screen()
t = Turtle("turtle")
t.speed(-1)

def dragging(x, y):  # These parameters will be the mouse position
    t.ondrag(None)
    t.setheading(t.towards(x, y))
    t.goto(x, y)
    t.ondrag(dragging)

def clickRight():
    t.clear()

def main():  # This will run the program
    turtle.listen()
    
    t.ondrag(dragging)  # When we drag the turtle object call dragging
    turtle.onscreenclick(clickRight, 3)

    screen.mainloop()  # This will continue running main() 

main()

If you benefited from these tutorial please consider supporting me and the website by heading to the donation page. I put a lot of work into these tutorials and would appreciate any support you can provide.

Design & Development by Ibezio Logo