簡體   English   中英

如何使烏龜移動到光標上?

[英]How can I make my turtle move to my cursor?

我試圖將烏龜移到光標上以畫些東西,以便每次單擊時,烏龜都會去那里畫些東西。

我已經嘗試過onscreenclick(),onclick以及兩者的許多組合,感覺好像做錯了什么,但是我不知道是什么。

from turtle import*
import random
turtle = Turtle()
turtle.speed(0)
col  = ["red","green","blue","orange","purple","pink","yellow"]
a = random.randint(0,4)
siz = random.randint(100,300)
def draw():
    for i in range(75):
        turtle.color(col[a])
        turtle.forward(siz)
        turtle.left(175)

TurtleScreen.onclick(turtle.goto)

任何幫助都會很棒,謝謝您的時間(如果您幫助我!

您調用的不是什么方法,而是調用的是什么對象:

TurtleScreen.onclick(turtle.goto)

TurtleScreen是一個類,您需要在屏幕實例上調用它。 而且,由於您要除了turtle.goto之外還調用drawturtle.goto您需要定義自己的函數,同時調用這兩個函數:

screen = Screen()
screen.onclick(my_event_handler)

通過上述修復和其他調整,對代碼進行了重做:

from turtle import Screen, Turtle, mainloop
from random import choice, randint

COLORS = ["red", "green", "blue", "orange", "purple", "pink", "yellow"]

def draw():
    size = randint(100, 300)

    # make turtle position center of drawing
    turtle.setheading(0)
    turtle.setx(turtle.xcor() - size/2)

    turtle.pendown()

    for _ in range(75):
        turtle.color(choice(COLORS))
        turtle.forward(size)
        turtle.left(175)

    turtle.penup()

def event_handler(x, y):
    screen.onclick(None)  # disable event handler inside event handler

    turtle.goto(x, y)

    draw()

    screen.onclick(event_handler)

turtle = Turtle()
turtle.speed('fastest')
turtle.penup()

screen = Screen()
screen.onclick(event_handler)

mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM