Alex
Alex

Reputation: 27

How to see if a mouse click is on a turtle in python

I want to have the program check if a mouse click is on a turtle. Like every time the user clicks the program checks if there is a turtle there (Like selecting pieces in a game, you click on the screen and if the click is on a piece, aka turtle, you select it. If not, nothing happens)

Upvotes: 1

Views: 1709

Answers (2)

ggorlen
ggorlen

Reputation: 56885

In addition to onclick there's distance. This is useful for finding all of the turtles near a click (potentially expensive if you loop over all turtles) and handling multiple turtles that are stacked on top of each other.

onclick example:

from turtle import Screen, Turtle


def make_turtle(x, y):
    t = Turtle()

    def handle_click(x, y):
        t.color("red")
        print(x, y)

    t.onclick(handle_click)
    t.penup()
    t.shape("square")
    t.shapesize(.9, .9)
    t.goto(x * grid_size, y * grid_size)
    t.pendown()


grid_size = 20
Screen().tracer(0)

for x in range(-10, 10):
    for y in range(-10, 10):
        make_turtle(x, y)

Screen().tracer(1)
Screen().mainloop()

distance example (tweak constants to adjust behavior):

from turtle import Screen, Turtle


def handle_click(x, y):
    print(x, y)

    for t in turtles:
        if t.distance(x, y) < 25:
            t.color("red")


def make_turtle(x, y):
    t = Turtle()
    turtles.append(t)
    t.penup()
    t.shape("square")
    t.shapesize(1.5, 1.5)
    t.goto(x * grid_size, y * grid_size)
    t.pendown()


grid_size = 60
Screen().tracer(0)
turtles = []

for x in range(-5, 5):
    for y in range(-5, 5):
        make_turtle(x, y)

Screen().onclick(handle_click)
Screen().tracer(1)
Screen().mainloop()

Upvotes: 1

furas
furas

Reputation: 142641

You have function turtle.onclick(my_function) which runs my_function only when you click turtle. If you click outside turtle, then it doesn't run my_function

If you have many turtles then you can use it to assign different functions to different turtles.

Doc: onclick

Upvotes: 1

Related Questions