/Lib/lib-tk/tkColorChooser.py

http://unladen-swallow.googlecode.com/ · Python · 72 lines · 24 code · 17 blank · 31 comment · 7 complexity · b3d559de9386930b133807fac885cc06 MD5 · raw file

  1. # tk common colour chooser dialogue
  2. #
  3. # this module provides an interface to the native color dialogue
  4. # available in Tk 4.2 and newer.
  5. #
  6. # written by Fredrik Lundh, May 1997
  7. #
  8. # fixed initialcolor handling in August 1998
  9. #
  10. #
  11. # options (all have default values):
  12. #
  13. # - initialcolor: colour to mark as selected when dialog is displayed
  14. # (given as an RGB triplet or a Tk color string)
  15. #
  16. # - parent: which window to place the dialog on top of
  17. #
  18. # - title: dialog title
  19. #
  20. from tkCommonDialog import Dialog
  21. #
  22. # color chooser class
  23. class Chooser(Dialog):
  24. "Ask for a color"
  25. command = "tk_chooseColor"
  26. def _fixoptions(self):
  27. try:
  28. # make sure initialcolor is a tk color string
  29. color = self.options["initialcolor"]
  30. if isinstance(color, tuple):
  31. # assume an RGB triplet
  32. self.options["initialcolor"] = "#%02x%02x%02x" % color
  33. except KeyError:
  34. pass
  35. def _fixresult(self, widget, result):
  36. # result can be somethings: an empty tuple, an empty string or
  37. # a Tcl_Obj, so this somewhat weird check handles that
  38. if not result or not str(result):
  39. return None, None # canceled
  40. # to simplify application code, the color chooser returns
  41. # an RGB tuple together with the Tk color string
  42. r, g, b = widget.winfo_rgb(result)
  43. return (r/256, g/256, b/256), str(result)
  44. #
  45. # convenience stuff
  46. def askcolor(color = None, **options):
  47. "Ask for a color"
  48. if color:
  49. options = options.copy()
  50. options["initialcolor"] = color
  51. return Chooser(**options).show()
  52. # --------------------------------------------------------------------
  53. # test stuff
  54. if __name__ == "__main__":
  55. print "color", askcolor()