colorchooser.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # tk common color 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: color 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 tkinter.commondialog 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())