Colored Boxes

Back to index

This is the first assignment in which Tkinter is used to create rectangles. As a first step in this lesson, get the following sample program up and running.
#!/usr/bin/python # basic canvas with lines and rectangle from Tkinter import * from tkColorChooser import askcolor master = Tk() w = Canvas(master, width=400, height=300) w.pack() for y in range(0,300,20): w.create_line(0,y,400,y) for x in range(0,400,20): w.create_line(x,0,x,300,fill="red",dash=(3,3)) w.create_line(200,0,200,300,fill="blue") w.create_line(0,150,400,150,fill="blue") for x in [10,180,350]: for y in [10,130,250]: c=askcolor() w.create_rectangle(x,y,x+40,y+40,fill=c[1]) mainloop()
Youu should experiment create_rectangle to make sure you understand how it works. Also the dash attribute should be inspected and experimented with.

However, one item which could use a little more explanation is the following two lines from the sample program:

c=askcolor() w.create_rectangle(x,y,x+40,y+40,fill=c[1])
The askcolor function is defined in tkColorChooser package and it returns values which define the selected color in two forms:
((66,69,214), '#404bdb')
Thus, the c[1] refers to the second item in the array returned by askcolor. (NOTE: tkColorChooser may not be available in all implementations of Python and so a work around may be necessary.)
ASSIGNMENT:

Make the following changes to the sample program:

  1. Alter the dashed lines so that the dashes are two units long and the spaces between the dashes are eight units wide
  2. Create an evenly spaced array of sixteen boxes in a 4x4 pattern
  3. Instead of asking the user to assign colors, create an array of sixteen different colors using hexadecimal values
  4. Eliminate the lines related to tkColorChooser