logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

colorchooser.py (2660B)


  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. from tkinter.commondialog import Dialog
  11. __all__ = ["Chooser", "askcolor"]
  12. class Chooser(Dialog):
  13. """Create a dialog for the tk_chooseColor command.
  14. Args:
  15. master: The master widget for this dialog. If not provided,
  16. defaults to options['parent'] (if defined).
  17. options: Dictionary of options for the tk_chooseColor call.
  18. initialcolor: Specifies the selected color when the
  19. dialog is first displayed. This can be a tk color
  20. string or a 3-tuple of ints in the range (0, 255)
  21. for an RGB triplet.
  22. parent: The parent window of the color dialog. The
  23. color dialog is displayed on top of this.
  24. title: A string for the title of the dialog box.
  25. """
  26. command = "tk_chooseColor"
  27. def _fixoptions(self):
  28. """Ensure initialcolor is a tk color string.
  29. Convert initialcolor from a RGB triplet to a color string.
  30. """
  31. try:
  32. color = self.options["initialcolor"]
  33. if isinstance(color, tuple):
  34. # Assume an RGB triplet.
  35. self.options["initialcolor"] = "#%02x%02x%02x" % color
  36. except KeyError:
  37. pass
  38. def _fixresult(self, widget, result):
  39. """Adjust result returned from call to tk_chooseColor.
  40. Return both an RGB tuple of ints in the range (0, 255) and the
  41. tk color string in the form #rrggbb.
  42. """
  43. # Result can be many things: an empty tuple, an empty string, or
  44. # a _tkinter.Tcl_Obj, so this somewhat weird check handles that.
  45. if not result or not str(result):
  46. return None, None # canceled
  47. # To simplify application code, the color chooser returns
  48. # an RGB tuple together with the Tk color string.
  49. r, g, b = widget.winfo_rgb(result)
  50. return (r//256, g//256, b//256), str(result)
  51. #
  52. # convenience stuff
  53. def askcolor(color=None, **options):
  54. """Display dialog window for selection of a color.
  55. Convenience wrapper for the Chooser class. Displays the color
  56. chooser dialog with color as the initial value.
  57. """
  58. if color:
  59. options = options.copy()
  60. options["initialcolor"] = color
  61. return Chooser(**options).show()
  62. # --------------------------------------------------------------------
  63. # test stuff
  64. if __name__ == "__main__":
  65. print("color", askcolor())