With this recipe we see an example of all the valid types of color specification. Basically there are two methods of specifying color that Tkinter recognizes, but there are a total of nine ways of expressing these. Thanks to the Python designers, the system is flexible and accepts all without complaint.
Execute the program shown in exactly the same way as all the examples in Chapter 2, Drawing Fundamental Shapes and you will see three disks filled with red and four with blue. Each is specified differently.
# color_arithmetic_1.py #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> from Tkinter import * root = Tk() root.title('Ways of Specifying Color') cw = 270 # canvas width ch = 80 # canvas height canvas_1 = Canvas(root, width=cw, height=ch, background="white") canvas_1.grid(row=0, column=1) # specify bottom-left and top-right as a set of four numbers named # 'xy' named_color_1 = "light blue" # ok named_color_2 = "lightblue" # ok named_color_3 = "LightBlue" # ok named_color_4 = "Light Blue" # ok named_color_5 = "Light Blue" # Name error - not ok: Tcl Error, # unknown color name rgb_color = "rgb(255,0,0)" # Unknown color name. #rgb_percent_color = rgb(100%, 0%, 0%) # Invalid syntax rgb_hex_1 = "#ff0000" # ok - 16.7 million colors rgb_hex_2 = "#f00" # ok rgb_hex_3 = "#ffff00000000" # ok - a ridiculous number tk_rgb = "#%02x%02x%02x" % (128, 192, 200) printtk_rgb y1, width, height = 20,20,20 canvas_1.create_oval(10,y1,10+width,y1+height, fill= rgb_hex_1) canvas_1.create_oval(30,y1,30+width,y1+height, fill= rgb_hex_2) canvas_1.create_oval(50,y1,50+width,y1+height, fill= rgb_hex_3) canvas_1.create_oval(70,y1,70+width,y1+height, fill= tk_rgb) y1 = 40 canvas_1.create_oval(10,y1,10+width,y1+height, fill= named_color_1) canvas_1.create_oval(30,y1,30+width,y1+height, fill= named_color_2) canvas_1.create_oval(50,y1,50+width,y1+height, fill= named_color_3) canvas_1.create_oval(70,y1,70+width,y1+height, fill= named_color_4) root.mainloop()#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Tkinter has the different name strings defined in a dictionary somewhere inside the Tkinter module library.
Some other languages specify colors as a numerical mixture of red, green and blue with each band ranging from 0 to 255 as a tuple. For example, pure red would be (255,0,0), pure green would be (0,255,0) and blue would be (0,0,255). A mixture of lots of red with a medium amount of green and just a touch of blue could be (230, 122, 20). These tuples are not recognized by Tkinter but the following line of Python code will convert any color_tuple into a color hex number that Tkinter will recognize and use as a color:
Tkinter_hex_color = '#%02x%02x%02x' % color_tuple
,
where color_tuple = (230, 122, 20)
or whatever numbers we choose to have in the tuple.
52.15.42.128