Recognize a user clicking a specific turtle?

716 views Asked by At

So I have a model of the solar system. It creates 8 (sorry Pluto) turtle objects that orbit the Sun in a StepAll function that incrementally move each turtle at the same time on the screen. I want to add a function that allows for a user to click on a specific planet and for it to display specific information about the unique turtle that was clicked (display info about planets etc.)

Is this possible?

If not I have thought of buttons, but making them move along with the planets seems tricky... Any help would be appreciated. Thanks!

2

There are 2 answers

0
cdlane On BEST ANSWER

It just so happens that I've a four inner planet simulator left over from answering another SO question that we can plug onclick() methods into to see how well this works with moving turtles:

""" Simulate motion of Mercury, Venus, Earth, and Mars """

from turtle import Turtle, Screen

planets = {
    'mercury': {'diameter': 0.383, 'orbit': 58, 'speed': 7.5, 'color': 'gray'},
    'venus': {'diameter': 0.949, 'orbit': 108, 'speed': 3, 'color': 'yellow'},
    'earth': {'diameter': 1.0, 'orbit': 150, 'speed': 2, 'color': 'blue'},
    'mars': {'diameter': 0.532, 'orbit': 228, 'speed': 1, 'color': 'red'},
}

def setup_planets(planets):
    for planet in planets:
        dictionary = planets[planet]
        turtle = Turtle(shape='circle')

        turtle.speed("fastest")  # speed controlled elsewhere, disable here
        turtle.shapesize(dictionary['diameter'])
        turtle.color(dictionary['color'])
        turtle.penup()
        turtle.sety(-dictionary['orbit'])
        turtle.pendown()

        dictionary['turtle'] = turtle

        turtle.onclick(lambda x, y, p=planet: on_click(p))

    revolve()

def on_click(planet):

    p = screen.textinput("Guess the Planet", "Which planet is this?")

    if p and planet == p:
        pass  # do something interesting

def revolve():

    for planet in planets:
        dictionary = planets[planet]
        dictionary['turtle'].circle(dictionary['orbit'], dictionary['speed'])

    screen.ontimer(revolve, 50)

screen = Screen()

setup_planets(planets)

screen.mainloop()

Generally, it works fine. Sometimes the planets stop in their orbits while the textinput() dialog panel is visible, other times they don't. I'll leave this issue for the OP to resolve, as needed.

enter image description here

0
furas On

You can assign to every turtle individual function using turtle.onclick()

import turtle

# --- functions ---

def on_click_1(x, y):
    print('Turtle 1 clicked:', x, y)

def on_click_2(x, y):
    print('Turtle 2 clicked:', x, y)

def on_click_screen(x, y):
    print('Screen clicked:', x, y)

# --- main ---

a = turtle.Turtle()
a.bk(100)
a.onclick(on_click_1)

b = turtle.Turtle()
b.fd(100)
b.onclick(on_click_2)

turtle.onscreenclick(on_click_screen)

turtle.mainloop()