1

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)

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Alex
  • 27
  • 7

2 Answers2

1

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

furas
  • 134,197
  • 12
  • 106
  • 148
1

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:

import turtle


def make_turtle(x, y):
    t = turtle.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
turtle.tracer(0)

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

turtle.tracer(1)
turtle.mainloop()

distance example:

import turtle


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

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


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


grid_size = 20
turtle.tracer(0)
turtles = []

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

turtle.Screen().onclick(handle_click)
turtle.tracer(1)
turtle.mainloop()
ggorlen
  • 44,755
  • 7
  • 76
  • 106