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