DaCR
DaCR

Reputation: 19

invalid color argument for pygame

I created this class:

class randcolour:
    def __init__(self):
        self.r = random.randint(0,255)
        self.g = random.randint(0,255)
        self.b = random.randint(0,255)
    def return_colour(self):
        return (self.r, self.g, self.b)
colour = randcolour()
colour.return_colour()

When I try to use it in

pygame.draw.rect(screen,colour,[btnx,btny,btnwi,btnle])

I get this error:

TypeError: invalid color argument

What is wrong here?

Upvotes: 0

Views: 8931

Answers (2)

Kory
Kory

Reputation: 11

Another option is to use len and getitem hooks in your class. These are what let you access the items in a list behind the scenes. So something like this could work:

class randcolour:
    def __init__(self):
        self.r = random.randint(0,255)
        self.g = random.randint(0,255)
        self.b = random.randint(0,255)

        self.colour = [self.r, self.g, self.b]

    def __len__(self):
        return 3 #Hard coding three, could use len(self.colour) if you like

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

Then

pygame.draw.rect(screen, colour, [btnx, btny, btnwi, btnle])

This way pygame can 'know' about your randcolour as a sequence type. Check out: https://docs.python.org/2/reference/datamodel.html#emulating-container-types for more info on emulating containers.

Note: Going by memory here, but I'm pretty sure that pygame will work with len and getitem with the colour. It definitely does for things like pygame.Rects.

Upvotes: 0

chepner
chepner

Reputation: 530960

PyGame doesn't know anything about your custom color class; specifically, it expects a tuple of numbers specifying the color, and it doesn't know that it needs to call your object's return_color method to get such a tuple. You need to call it yourself.

pygame.draw.rect(screen,colour.return_color(),[btnx,btny,btnwi,btnle])

Upvotes: 4

Related Questions