我正在尝试将乌龟移到光标上以绘制一些东西,以便每次单击时,乌龟都会去那里绘制一些东西。
我已经尝试过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)
任何帮助都会很棒,谢谢您的时间(如果您帮助我!;)
答案 0 :(得分:0)
调用的方法不是很多,而是调用的对象是什么:
TurtleScreen.onclick(turtle.goto)
TurtleScreen
是一个类,您需要在屏幕实例上调用它。而且,由于除了draw
之外,还想调用turtle.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()