python-3.x Pygame ValueError:无效颜色参数问题

x759pob2  于 2023-04-08  发布在  Python
关注(0)|答案(3)|浏览(288)

我试图用pygame制作一个矩形的彩虹,但我遇到了一个问题,说“ValueError:无效的颜色参数”

import pygame
pygame.init()

width = 400
height = 400
window_size = (width , height)
screen = pygame.display.set_mode(window_size)

colour = pygame.color.Color('#646400')

row = 0
done = False
while not done:
    increment = 255 / 100
    while row <= height:
        pygame.draw.rect(screen, colour, (0, row, width, row + increment))
        pygame.display.flip()
        if colour[2] + increment < 255:
            colour[2] += increment
        row += increment

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
pygame.quit()
zpf6vheq

zpf6vheq1#

最简单的方法是使用tuple的RGB值作为颜色:

color = (0x64, 0x64, 0x00)  # equal to #646400

然后将它作为第二个参数传递给draw.rect(),就像你已经做过的那样:

pygame.draw.rect(screen, color, (0, row, width, row + increment))
qc6wkl3g

qc6wkl3g2#

你需要改变这个,colour = pygame.color.Color('#646400'),因为它将更容易去与RGB颜色在一个list。改变它:

colour = [0,0,100]

或者任何你想要的颜色,也许混合它们得到彩虹的结果。这是我会做的。代码的结果是一个渐变的蓝色。但是正如我之前提到的,你可以改变它。但是记住你不能使用tuple!因为它们是不可变的。

d7v8vwbk

d7v8vwbk3#

正如许多其他人所建议的那样,PyGame不支持HTML符号颜色字符串。
但是转换这些是相当简单的:

# Convert HTML-like colour hex-code to integer triple tuple
# E.g.: "#892da0" -> ( 137, 45, 160 )
def hexToColour( hash_colour ):
    """Convert a HTML-hexadecimal colour string to an RGB triple-tuple"""
    red   = int( hash_colour[1:3], 16 )
    green = int( hash_colour[3:5], 16 )
    blue  = int( hash_colour[5:7], 16 )
    return ( red, green, blue )

...

colour = hexToColour( '#646400' )

通常不需要将它们转换为Color对象来使用它们。

相关问题