如何使我的乌龟移动到光标?

2024-04-26 07:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着把乌龟移到我的光标上,这样每次我点击,乌龟都会去那里画东西

我已经尝试了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)

任何帮助都会很好,谢谢你的时间(如果你帮我的话!)


Tags: 方法fromimportcolrandomgreenredspeed
1条回答
网友
1楼 · 发布于 2024-04-26 07:29:58

与其说是调用什么方法,不如说是在调用什么对象:

TurtleScreen.onclick(turtle.goto)

TurtleScreen是一个类,您需要在屏幕实例上调用它。由于除了turtle.goto之外,您还想调用draw,因此需要定义自己的函数来调用这两个函数:

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

相关问题 更多 >