python - 如何让 turtle 具有随机颜色?

标签 python turtle-graphics python-turtle

如何修复此代码以使 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 窗口:

enter image description here

关于python - 如何让 turtle 具有随机颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46091442/

相关文章:

python - 如何在 Python Turtle 中定位文本?

python - 让 turtle 保持在一个正方形内,没有输出,也没有错误

python - 使用递归绘制雪花

python - turtle 有类似 Ctrl-Z(撤消)功能吗?

python - turtle 和 turtle 有什么区别?

python - pandas 根据另一列获取 True 值的(开始、结束)位置

python - Django 或 python 与 Mercurial 一起使用时如何处理 pyc 文件?

python - INSERT IGNORE 与 IN list()

python - 使用 Python C API 时 MIDIGetNumberOfDestinations 返回 0

python - 使用Python中的Turtle模块将缩小的 turtle 向上移动窗口屏幕