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# 12# options (all have default values): 13# 14# - initialcolor: color to mark as selected when dialog is displayed 15# (given as an RGB triplet or a Tk color string) 16# 17# - parent: which window to place the dialog on top of 18# 19# - title: dialog title 20# 21 22from tkinter.commondialog import Dialog 23 24__all__ = ["Chooser", "askcolor"] 25 26 27# 28# color chooser class 29 30class Chooser(Dialog): 31 "Ask for a color" 32 33 command = "tk_chooseColor" 34 35 def _fixoptions(self): 36 try: 37 # make sure initialcolor is a tk color string 38 color = self.options["initialcolor"] 39 if isinstance(color, tuple): 40 # assume an RGB triplet 41 self.options["initialcolor"] = "#%02x%02x%02x" % color 42 except KeyError: 43 pass 44 45 def _fixresult(self, widget, result): 46 # result can be somethings: an empty tuple, an empty string or 47 # a Tcl_Obj, so this somewhat weird check handles that 48 if not result or not str(result): 49 return None, None # canceled 50 51 # to simplify application code, the color chooser returns 52 # an RGB tuple together with the Tk color string 53 r, g, b = widget.winfo_rgb(result) 54 return (r/256, g/256, b/256), str(result) 55 56 57# 58# convenience stuff 59 60def askcolor(color = None, **options): 61 "Ask for a color" 62 63 if color: 64 options = options.copy() 65 options["initialcolor"] = color 66 67 return Chooser(**options).show() 68 69 70# -------------------------------------------------------------------- 71# test stuff 72 73if __name__ == "__main__": 74 print("color", askcolor()) 75