所以我有太阳系的模型。它创建了8个(对不起的冥王星)乌龟对象,它们在StepAll函数中绕太阳运行,该函数在屏幕上同时递增地移动每只乌龟。我想添加一个功能,允许用户点击特定的星球,并显示有关所点击的独特乌龟的特定信息(显示有关行星的信息等)
这可能吗?
如果不是我想到按钮,但让它们与行星一起移动似乎很棘手......任何帮助都会受到赞赏。谢谢!
答案 0 :(得分:0)
您可以使用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()
答案 1 :(得分:0)
恰好我已经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解决。