Letting users select colors on the fly
The standard color selection dialog isn’t just another pretty face—scripts can pass the
hexadecimal color string it returns to the bg and fg widget color configuration options
we met earlier. That is, bg and fg accept both a color name (e.g., blue) and an ask
color hex RGB result string that starts with a # (e.g., the #8080ff in the last output line
of the prior section).
This adds another dimension of customization to tkinter GUIs: instead of hardcoding
colors in your GUI products, you can provide a button that pops up color selectors that
let users choose color preferences on the fly. Simply pass the color string to widget
config methods in callback handlers, as in Example 8-11.
Example 8-11. PP4E\Gui\Tour\setcolor.py
from tkinter import *
from tkinter.colorchooser import askcolor
def setBgColor():
(triple, hexstr) = askcolor()
if hexstr:
print(hexstr)
push.config(bg=hexstr)
root = Tk()
push = Button(root, text='Set Background Color', command=setBgColor)
push.config(height=3, font=('times', 20, 'bold'))
push.pack(expand=YES, fill=BOTH)
root.mainloop()
This script creates the window in Figure 8-16 when launched (its button’s background
is a sort of green, but you’ll have to trust me on this). Pressing the button pops up the
color selection dialog shown earlier; the color you pick in that dialog becomes the
background color of this button after you press OK.
Figure 8-16. setcolor main window
Dialogs | 437