Python Forum

Full Version: Using color in python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
(Sep-22-2019, 10:54 PM)Windspar Wrote: [ -> ]You can always wrap it.

Can we also have a dictionary type property facilitating access to all existing pairs of ColorNames & ColorValues in one statement?
Is this what you are talking about.
import pygame

class PygameColors:
    def __init__(self):
        self.__dict__.update(pygame.color.THECOLORS)

    def __getitem__(self, key):
        return self.__dict__[key]

    def add(self, name, r, g, b, a=255):
        if name not in vars(self).keys():
            setattr(self, name, pygame.Color(r, g, b, a))
        else:
            print("Color already exists:", name)

color = PygameColors()

print("white:", color["white"], color.white, pygame.Color("white"))
(Sep-23-2019, 10:27 PM)Windspar Wrote: [ -> ]Is this what you are talking about.

I meant contents of the inbuilt color dictionary. Adding function colordict(), to the code provided by you, has met this requirement, as placed below:

import pygame
 
class PygameColors:
    def __init__(self):
        self.__dict__.update(pygame.color.THECOLORS)
 
    def __getitem__(self, key):
        return self.__dict__[key]
 
    def add(self, name, r, g, b, a=255):
        if name not in vars(self).keys():
            setattr(self, name, pygame.Color(r, g, b, a))
        else:
            print("Color already exists:", name)

    def colordict(self):
        return self.__dict__
 
color = PygameColors()
print(color.colordict())
Why not just print it out this way
print(color.__dict__)
(Sep-28-2019, 04:09 PM)SheeppOSU Wrote: [ -> ]Why not just print it out this way

That is simplest. Thanks.

It might also be desirable to avoid naming a user created object as "color" as that happens to be the name of a built-in object in pygame (imported into the class in question).
You can also do this.
print(vars(color))
(Sep-30-2019, 10:39 AM)Windspar Wrote: [ -> ]You can also do this.

Very Nice. Thanks.
Pages: 1 2