使用 Turtle 生成 Python 随机颜色

问题描述 投票:0回答:3

我需要使用 r g b 值生成随机颜色来填充这些矩形以进行 python 学校作业,尽管我相当确定我将其格式化为 Python 文档,但我遇到了错误的颜色序列错误建议。

r = random.randrange(0, 257, 10)
g = random.randrange(0, 257, 10)
b = random.randrange(0, 257, 10)


def drawRectangle(t, w, h):
    t.setx(random.randrange(-300, 300))
    t.sety(random.randrange(-250, 250))
    t.color(r, g, b)
    t.begin_fill()
    for i in range(2):
        t.forward(w)
        t.right(90)
        t.forward(h)
        t.right(90)
    t.end_fill()
    t.penup()

我很困惑为什么 t.color(r, g, b) 不产生随机颜色?

python random colors turtle-graphics
3个回答
4
投票

turtle.colormode 需要设置为 255 才能以十六进制代码或 R G B 给出颜色字符串。

添加

screen.colormode(255)

不再返回错误。


1
投票

你的变量 r g 和 b 不是全局的。您要么必须在函数顶部添加全局声明,要么将它们添加为参数。

def my_function(r, g, b):
    # some stuff

或者...

def myfunction():
    global r, g, b
    # some stuff

0
投票
import turtle as t 
import random

timmy = t.Turtle()
t.colormode(255)


def random_color():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    random_color = (r, g, b)
    return random_color


timmy.color(random_color())
© www.soinside.com 2019 - 2024. All rights reserved.