2016-12-16 153 views
-1

所以我有一個太陽系的模型。它創建了8個(對不起冥王星)烏龜物體,它們在StepAll函數中繞太陽運行,在屏幕上同時遞增移動每隻烏龜。我想添加一個功能,允許用戶點擊一個特定的星球,併爲它顯示有關被點擊的獨特烏龜的具體信息(顯示有關行星的信息等)。識別用戶點擊特定的龜?

這可能嗎?

如果沒有我想到按鈕,但讓他們與行星一起移動似乎棘手...任何幫助將不勝感激。謝謝!

+0

[turtle.onclick(樂趣,BTN = 1,加=無)](https://docs.python.org/2/library/turtle.html#using-events) - 其分配單擊事件到每個龜。 – furas

+1

順便說一句:背景中的龜使用了具有更多功能的Tkinter。 – furas

回答

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解決此問題。

enter image description here

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