识别出点击特定海龟的用户?

Recognize a user clicking a specific turtle?

所以我有一个太阳系模型。它在 StepAll 函数中创建了 8 个(对不起 Pluto)围绕太阳运行的海龟对象,该函数在屏幕上同时递增地移动每只海龟。我想添加一个功能,允许用户单击特定行星并显示有关被单击的唯一乌龟的特定信息(显示有关行星等的信息)

这可能吗?

如果没有,我已经想到了按钮,但让它们与行星一起移动似乎很棘手...任何帮助将不胜感激。谢谢!

您可以使用 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()

碰巧我有一个 four inner planet simulator left over from answering another SO question,我们可以将 onclick() 方法插入其中,看看它对移动海龟的效果如何:

""" 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()

一般情况下,它工作正常。有时,当 textinput() 对话框面板可见时,行星会停在它们的轨道上,有时则不会。我将根据需要将此问题留给 OP 解决。