Hov can I make a string triplet to a RGB color? Like this:

color = "255,255,255"
background.fill((color))

This code gives me "invalid color argument". Why I want to do it this way? This string is saved in a file.

有帮助吗?

解决方案

pygame.Surface.fill expects:

The color argument can be either a RGB sequence, a RGBA sequence or a mapped color index. If using RGBA, the Alpha (A part of RGBA) is ignored unless the surface uses per pixel alpha (Surface has the SRCALPHA flag).

You could try something like

def str2rgb(s):
    rgba = s.split(",")
    if len(rgba) not in (3, 4):
        return (0, 0, 0)
    return tuple(map(int, rgba))


>>> color = "255,255,255"
>>> str2rgb(color)
(255, 255, 255)
>>> color2 = "255,255,255,0"
>>> str2rgb(color2)
(255, 255, 255, 0)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top