Skip to content
Laviyx Learn

Try

Python Lab · Experiment 28

Draw rectangles, points and circles on a Canvas

PythonWeek 6JNTUH R22 · CS206ES

Aim

To write a Python program with Point, Rectangle and Circle classes and the functions draw_rectangle, draw_point and draw_circle, which draw these objects on a tkinter Canvas, using each rectangle's and circle's color attribute as its fill colour.

Algorithm

  1. Define a class Point with attributes x and y.
  2. Define a class Rectangle with attributes corner (the top-left Point), width, height and color.
  3. Define a class Circle with attributes center (a Point), radius and color.
  4. Write draw_rectangle(canvas, rect): find the opposite corner by adding the width and height to the top-left corner, and call canvas.create_rectangle with fill=rect.color.
  5. Write draw_point(canvas, point): draw a very small filled circle around the point, because a canvas cannot draw a single dot.
  6. Write draw_circle(canvas, circle): call canvas.create_oval with the square that surrounds the circle, from (x − r, y − r) to (x + r, y + r), and fill=circle.color.
  7. Create a window and a Canvas, create a few rectangles, points and circles, and draw each one with its function.
  8. Start mainloop() so the window stays open until the user closes it.

Program

Python
import tkinter as tk


class Point:
    """A point with x and y coordinates on the canvas."""

    def __init__(self, x, y):
        self.x = x
        self.y = y


class Rectangle:
    """A rectangle given by its top-left corner, width, height and colour."""

    def __init__(self, corner, width, height, color="white"):
        self.corner = corner
        self.width = width
        self.height = height
        self.color = color


class Circle:
    """A circle given by its centre point, radius and colour."""

    def __init__(self, center, radius, color="white"):
        self.center = center
        self.radius = radius
        self.color = color


def draw_rectangle(canvas, rect):
    x1 = rect.corner.x
    y1 = rect.corner.y
    x2 = x1 + rect.width
    y2 = y1 + rect.height
    canvas.create_rectangle(x1, y1, x2, y2, fill=rect.color, outline="black")


def draw_point(canvas, point):
    size = 3  # a point is drawn as a tiny circle of radius 3 pixels
    canvas.create_oval(point.x - size, point.y - size,
                       point.x + size, point.y + size, fill="black")


def draw_circle(canvas, circle):
    x = circle.center.x
    y = circle.center.y
    r = circle.radius
    canvas.create_oval(x - r, y - r, x + r, y + r, fill=circle.color, outline="black")


def main():
    root = tk.Tk()
    root.title("Shapes on a Canvas")
    canvas = tk.Canvas(root, width=420, height=320, bg="white")
    canvas.pack()

    # a. a rectangle with the default colour (white)
    box = Rectangle(Point(30, 30), 140, 80)
    draw_rectangle(canvas, box)

    # b. a rectangle that uses its color attribute as the fill colour
    blue_box = Rectangle(Point(220, 30), 160, 80, "lightblue")
    draw_rectangle(canvas, blue_box)

    # c. three points
    for point in [Point(50, 170), Point(100, 170), Point(150, 170)]:
        draw_point(canvas, point)

    # d. a few Circle objects
    circles = [
        Circle(Point(80, 250), 40, "orange"),
        Circle(Point(210, 230), 30, "lightgreen"),
        Circle(Point(320, 220), 50, "pink"),
    ]
    for circle in circles:
        draw_circle(canvas, circle)

    root.mainloop()


main()

Output

The program opens a window titled "Shapes on a Canvas" with a white drawing area 420 pixels wide and 320 pixels high. It shows:

  • At the top left, a white rectangle with a black border, 140 × 80 pixels, with its top-left corner at (30, 30). This is part a, a rectangle with the default colour.
  • At the top right, a light blue rectangle with a black border, 160 × 80 pixels, with its top-left corner at (220, 30). This is part b, filled with its color attribute.
  • In the middle left, three small black dots in a row at (50, 170), (100, 170) and (150, 170). These are the points of part c.
  • Along the bottom, three filled circles with black borders: an orange circle of radius 40 centred at (80, 250), a light green circle of radius 30 centred at (210, 230), and a pink circle of radius 50 centred at (320, 220). These are the circles of part d.

The window stays open until you close it. Nothing is printed in the terminal.

How it works

The syllabus problem comes from the "Think Python" book, which uses its own drawing module. This program uses Python's built-in tkinter module instead, so it runs with no extra installation.

In a tkinter Canvas, the point (0, 0) is the top-left corner, x grows to the right and y grows downwards (not upwards as in maths).

create_rectangle(x1, y1, x2, y2) needs two opposite corners, so draw_rectangle works out the bottom-right corner from the top-left corner, the width and the height. create_oval(x1, y1, x2, y2) draws the oval that fits inside that box; when the box is a square of side 2r, the oval is a circle of radius r.

Each object stores its own colour in the color attribute, and the drawing function reads it, so the same function draws rectangles of any colour. tkinter accepts colour names such as "orange" or "lightblue" and codes such as "#ff8800".

Common mistakes

  • Passing width and height to create_rectangle as if they were the second corner, such as create_rectangle(30, 30, 140, 80). The last two numbers are the x and y of the opposite corner, so the rectangle comes out the wrong size.

  • Passing the centre and radius straight to create_oval. It needs the box around the circle: (x - r, y - r, x + r, y + r).

  • Forgetting root.mainloop(). The script then ends at once and the window closes (or never appears).

  • Expecting y to grow upwards. On a tkinter canvas a bigger y value is lower down the window.

Viva questions

Try to answer each one aloud before you open it.

  • What is a Canvas in tkinter?

    A Canvas is a widget, a rectangular area of the window, on which you can draw lines, rectangles, ovals, polygons, text and images.

  • How does create_oval draw a circle?

    create_oval(x1, y1, x2, y2) draws the oval that fits inside the box with corners (x1, y1) and (x2, y2). If the box is a square, the oval is a circle.

  • Where is the point (0, 0) on a tkinter canvas?

    At the top-left corner. x increases to the right and y increases downwards.

  • What is an attribute of an object?

    A named value stored inside the object, such as rect.width or rect.color. Attributes are usually set in __init__ using self.

  • Why does draw_rectangle take the rectangle object instead of four numbers?

    The object keeps all its data (corner, size and colour) together. The function reads what it needs from the object, so callers pass one value, and adding an attribute such as color does not change how the function is called.

  • What does mainloop() do?

    It starts the event loop. The window stays open and keeps responding to the user (redrawing, closing, clicks) until it is closed.

Learn the concepts

All Python Programming Lab experiments →