Graphics color library

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ebautis
    New Member
    • Dec 2009
    • 1

    Graphics color library

    Is there a way to check if a user has input a valid color from the graphics color library? I'm planning to write a getValidColor() function for my program that accepts input from a user in the form of a string (i.e. "white" "blue" etc.) Help?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    What graphics color library are you referring to? In Tkinter, colors are represented "#000"-"#fff", "#000000"-"#ffffff", "#000000000 ", "#fffffffff ", and the basic colors like "green", "blue", etc. In the software I use in my work, SDS/2, colors are represented as tuples of the RGB values 0-255. You can create a function to test the validity of user input of these types. Following are two functions I wrote to test for SDS/2 colors:
    Code:
    def validColTup(s):
        '''
        Given a string representing a color tuple, return the tuple.
        Return tuple (255,0,0) if string has an invalid number
        or is formatted improperly.
        '''
        try:
            tt = eval(s)
        except:
            tt = s
        try:
            if False in [[False, True][0 <= i <= 255 or 0] for i in tt] or len(tt) != 3:
                Warning('Invalid color - using (255,0,0)')
                return 255,0,0
        except:
            Warning('Incorrect color tuple - using (255,0,0)')
            return 255,0,0 
        return tt
    
    import re
    color_patt = re.compile(r"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
    
    def validColorStr(s):
        '''
        A color tuple is represented by three integers between 0-255
        separated by commas.
        Examples:
            (255,0,0) - red
            (120,120,120) - gray
        Possible string input representing a color tuple.
        '255,0,0' and '120,120,120'
        Test a string for proper form to represent a color tuple.
        Raise an exception if string is not valid.    '''
        # there must be no spaces
        if len(s.split()) == 1:
            colList = s.split(',')
            # R,G,B
            if len(colList) == 3:
                # check each primary color for validity
                if None not in [color_patt.match(octet) for octet in colList]:
                    return s
        raise ValueError

    Comment

    Working...