Python上是否有一个包含各种颜色的文件?

2024-05-18 15:32:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理几个Pygame项目,尽管将我从上一个文件中制作的一些颜色复制并粘贴到下一个文件中很不方便。我想知道是否有代码可以输入到我导入的文件中,或者有代码可以下载到Pygame中所有(或大部分)python颜色的文件中。谢谢

import pygame
pygame.init()

gameDisplay=pygame.display.set_mode((600,600)) 

pygame.display.set_caption("plz help")

white=(255,255,255)#r,g,b
black=(0,0,0)
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
aquamarine2=(118,238,198)

它可以工作并提供带有颜色的变量,但我希望有更多的种类和更简单更干净的方法来访问它。在网上,我只找到了找到特定颜色的方法,但没有批量和格式的方法可以复制和粘贴


Tags: 文件项目方法代码importinit颜色粘贴
2条回答

通过查看dictpygame.color.THECOLORS可以看到所有颜色。然而,所有名称和颜色值的dict都很大(当我写这篇文章时是657),因此要查看并找到您想要的东西可能会很麻烦

我经常发现自己试图找到颜色名称,并发现这段代码非常方便:

import pygame
from pprint import  pprint

color_list = [(c, v) for c, v in pygame.color.THECOLORS.items() if 'slategrey' in c]
pprint(color_list)

哪些产出:

[('darkslategrey', (47, 79, 79, 255)),
 ('slategrey', (112, 128, 144, 255))
 ('lightslategrey', (119, 136, 153, 255))]

我在交互式会话中这样做,以获得所有包含“slategrey”的名称,然后在我的实际代码中,我可以使用我想要的名称,如下所示:

slategrey = pygame.Color("slategrey")

然后在后面的代码引用中,它是这样的:

screen.fill(slategrey,  pygame.Rect(0, 0, 100, 100))

但是,如果您确实想查看pygame.color.THECOLORS中所有颜色的列表,您可以在定义颜色的pygamescolordict module中查看它们

正如Thomas Kläger在评论中指出的,pygame中有一个可能的颜色字符串列表

查看here以查看所有这些字符串及其RGB值

如果需要,可以通过pygame.color.THECOLORS访问此dict,但通常不需要。您只需将带有颜色名称的字符串传递给pygame的Color类,如下所示:

screen.fill(pygame.Color('red'),  pygame.Rect(  0, 0, 100, 100))
screen.fill(pygame.Color('plum'), pygame.Rect(100, 0, 100, 100))
screen.fill(pygame.Color('pink'), pygame.Rect(100, 0, 100, 100))

当然,没有列出每种可能的颜色,因为pygame中有256^3=16.777.216种可能的颜色(如果包含不同的alpha值,则为4.294.967.296)

相关问题 更多 >

    热门问题