tk_chooseColor , a Tk command, provides a color picker.
The following option-value pairs are possible as command line arguments:
Specifies the color to display in the color dialog when it pops up. Color must be in a form acceptable to the Tk_GetColor function.
Makes window the logical parent of the color dialog. The color dialog is displayed on top of its parent window.
Specifies a string to display as the title of the dialog box. If this option is not specified, then a default title will be displayed.
tk_chooseColor returns the name of the color selected by the user, in a form acceptable to Tk_GetColor. If the user cancels the operation, the command returns the empty string.
button .b -bg [tk_chooseColor -initialcolor gray -title "Choose color"]
A minimal example:
button .b_fg -text "Set Foreground Color" -command {fg_color} button .b_bg -text "Set Background Color" -command {bg_color} label .l -text "Foreground Color on Background Color" grid .b_fg .b_bg -sticky ew grid .l -row 1 -columnspan 2 -sticky ew proc fg_color { } { set color [tk_chooseColor] .l configure -fg $color } proc bg_color { } { set color [tk_chooseColor] .l configure -bg $color } wm title . {tk_chooseColor Example}
RS: A style note - no doubt this works as planned, but for more reusable (and also more compact) code, why not pass in the target widget, and the target attribute as well?
button .b_fg -text "Set Foreground Color" -command {color .l -fg} button .b_bg -text "Set Background Color" -command {color .l -bg} label .l -text "Foreground Color on Background Color" grid .b_fg .b_bg -sticky ew grid .l -row 1 -columnspan 2 -sticky ew proc color {w what} { set color [tk_chooseColor] $w configure $what $color }
For a tiny bit more safety, CL recommends instead
proc color {w what} { set color [tk_chooseColor] # "Cancel" means, "do nothing". if {$color eq {}} return $w configure $what $color }
Michael Schlenker contributed the following example of the use of this function over on comp.lang.tcl:
# set color variable to color value returned from tk_chooseColor set color [tk_chooseColor] # be .c an canvas with some objects in it , sets the -fill color of all # items to $color .c itemconfigure all -fill $color
Robert Heller also answered in the same comp.lang.tcl thread with this code fragment:
canvas .thecanvas pack .thecanvas .thecanvas create oval 0 0 50 50 -fill red -outline blue -tag theOval .thecanvas itemconfigure theOval -fill [ tk_chooseColor -initialcolor [.thecanvas itemcget theOval -fill]] .thecanvas itemconfigure theOval -outline [ tk_chooseColor -initialcolor [.thecanvas itemcget theOval -outline]]