title: Tkinter entry validation: Check for a valid color or portion of a color
body: <p>Recently, I have found that the validation option of Entry widgets is very useful (see <a href="https://stackoverflow.com/questions/4140437/python-tkinter-interactively-validating-entry-widget-content">this question</a>). I recently tried to write a validation command that would verify that the user was typing a hex code, or a named color. I wrote this, and it works great for hex codes, and it sporadically works for colors. It runs on every keypress, among other things. (<code>validate=ALL</code>)</p>
  
  <pre><code>def checkColorValid(P):
      global backgroundColor
      if not P:
          return True
  
      if P.lower() in colors:
          backgroundColor = P
          return True
  
      if P[0] == '#':
          try:
              if len(P) == 1:
                  return True
              int(P[1:], 16)
              if len(P) &lt; 8:
                  backgroundColor = P
                  return True
              else:
                  return False
          except ValueError:
              return False
  
      for color in colors:
          if color.startswith(P.lower()):
              return True
  </code></pre>
  
  <p><code>colors</code> is a list of all valid named colors.<br>
  The validation code works, unless you are trying to type a named color, and start typing the same character over and over again. Once that happens, the validation appears to simply stop working. It no longer runs at all, until you restart the program.</p>