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 25# 26# color chooser class 27 28class Chooser(Dialog): 29 "Ask for a color" 30 31 command = "tk_chooseColor" 32 33 def _fixoptions(self): 34 try: 35 # make sure initialcolor is a tk color string 36 color = self.options["initialcolor"] 37 if isinstance(color, tuple): 38 # assume an RGB triplet 39 self.options["initialcolor"] = "#%02x%02x%02x" % color 40 except KeyError: 41 pass 42 43 def _fixresult(self, widget, result): 44 # result can be somethings: an empty tuple, an empty string or 45 # a Tcl_Obj, so this somewhat weird check handles that 46 if not result or not str(result): 47 return None, None # canceled 48 49 # to simplify application code, the color chooser returns 50 # an RGB tuple together with the Tk color string 51 r, g, b = widget.winfo_rgb(result) 52 return (r/256, g/256, b/256), str(result) 53 54 55# 56# convenience stuff 57 58def askcolor(color = None, **options): 59 "Ask for a color" 60 61 if color: 62 options = options.copy() 63 options["initialcolor"] = color 64 65 return Chooser(**options).show() 66 67 68# -------------------------------------------------------------------- 69# test stuff 70 71if __name__ == "__main__": 72 print("color", askcolor()) 73