如何修复此代码以使 turtle 具有随机颜色?我希望能够通过单击使 turtle 转动并改变颜色。
import turtle
import random
turtle.colormode(255)
R = 0
G = 0
B = 0
def color(x, y):
turtle.color((R, G, B))
def turn(x, y):
turtle.left(10)
for i in range(10000):
turtle.onscreenclick(turn)
turtle.forward(1)
turtle.onrelease(color)
R = random.randrange(0, 257, 10)
B = random.randrange(0, 257, 10)
G = random.randrange(0, 257, 10)
def color(x, y):
turtle.color((R, G, B))
最佳答案
I want to be able to click then the turtle turns then change color.
我相信这符合您的描述:
import turtle
import random
def change_color():
R = random.random()
B = random.random()
G = random.random()
turtle.color(R, G, B)
def turn_and_change_color(x, y):
turtle.left(10)
change_color()
turtle.onscreenclick(turn_and_change_color)
def move_forward():
turtle.forward(1)
turtle.ontimer(move_forward, 25)
move_forward()
turtle.mainloop()
它使用计时器来保持 turtle 移动,而不是使用 range(10000)
循环,这也允许事件循环正常运行。它应该继续运行,直到您关闭 turtle 窗口:
关于python - 如何让 turtle 具有随机颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46091442/