2024-10-03 09:15:54 发布
网友
所以我有一个太阳系的模型。它创建了8个(对不起冥王星)乌龟对象,它们以StepAll函数的方式围绕太阳运行,在屏幕上同时递增地移动每个海龟。我想添加一个功能,允许用户点击一个特定的行星,让它显示关于被点击的独特海龟的特定信息(显示行星信息等)
这有可能吗?在
如果不是的话,我已经想到了按钮,但是让它们跟着行星移动似乎很棘手。。。任何帮助都将不胜感激。谢谢!在
碰巧我有一个four inner planet simulator left over from answering another SO question,我们可以把onclick()方法插入其中,看看这对移动的海龟有多有效:
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()对话框面板可见时,行星会停在它们的轨道上,其他时候则看不到。在
textinput()
您可以使用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()
方法插入其中,看看这对移动的海龟有多有效:一般来说,它工作得很好。有时当
textinput()
对话框面板可见时,行星会停在它们的轨道上,其他时候则看不到。在您可以使用turtle.onclick()为每个海龟分配单独的函数
相关问题 更多 >
编程相关推荐