15-110 Spring 2017


This lab is intended to develop your understanding of doing simple graphics with Python. We will be using the module Canvas from tkinter. We will also be using the module random to generate random colors for the shapes we draw. After we learn how to draw rectangles, we introduce the concept of a fractal in the last question and make you observe the recursive nature of fractals. That part is mainly intended to make you think recursively and enjoy a beautiful application of recursion.

When you are done with this lab, you should be able to do the following:

  1. Initialize a canvas of a certain size;
  2. Explain how the coordinate system works in the module Canvas;
  3. Draw rectangles on the canvas, possibly with borders, and possibly filled with color; and
  4. Use the module random to generate random integers.


  1. demo.py (CA demo)
  2. random_boxes.py
  3. triangle.py

tkinter Canvas

In order to draw in Python, you need to create a Canvas which you can do as follows:

import tkinter
# Remember, this means tkinter.___ to call functions and objects
from tkinter import Canvas
# Canvas object only can be called by itself. 

# First, create the window where our canvas will be displayed
window = tkinter.Tk()

#Then, create our canvas and pack it into the display window
c = Canvas(window, width=<width>, height=<height>)

Where you replace <width> and <height> with appropriate values. The width and height are expressed as a number of pixels.

See Quick Guide to tkinter.Canvas for information about drawing graphics. Just as a quick review, in a window, the coordinate system is upside down from what you might expect mathematically. The x coordinates increase from left to right, but the y coordinates increase from top to bottom. So the origin (0,0) is in the top left corner of the window.

To draw a rectangle using the Canvas, you need to create a new Rectangle and supply the coordinates of the top left and bottom right corners along with additional optional parameters:

c.create_rectangle(topleft_x, topleft_y, bottomright_x, bottomright_y, optional parameter(s))

For example, to create a red square with a blue border that has a top left coordinate of (100,100) and bottom right coordinate of (110, 110), you would execute:

c.create_rectangle(100, 100, 110, 110, fill ="red", outline="blue")

Part 1 - Random Numbers with Graphics

1.1. CA Demonstration

1.2 Student Activity

Part 2 - Recursion with Graphics

2.1 CA Demonstration

2.2 Student Activity