Canvas Widget

Graphics Programming With Canvas Widget

Canvas Widget is a tkinter class. The Canvas widget provides another way to create graphics (shapes, color fill, writing text annotations on the graphics images, etc).

We did advanced graphics programming and created GUI applications using Tkinter widgets such as Label, Button, and Entry widgets on previous pages.

We will do graphics programming and create GUI using the Canvas widget on this page.

Canvas Widget Class

Tkinter has many classes.  One of the classes is Canvas.  In this section, we will explain what a Canvas class is and how we can use the Canvas widget to do graphics programming. We will write programs to draw shapes such as lines, circles, polygons, graphs, etc.  These program examples will use procedural programming as well as class structure.

We will use basic coordinate geometry to draw shapes. The coordinates geometry basics are presented in the Appendix.

How to Create a Canvas to Draw Shapes On

In order to draw shapes, we first need to create a blank canvas to draw the shapes on. The steps to create a blank canvas are the same as we used to get a frame as in Tkinter Widgets chapter, namely

  1. Import the tkinter module as in statement below:

>>> from tkinter import *

2. Initialize the tkinter module and create a Tk root widget.

>>> root = Tk()

This statement initializes the tkinter module and creates a Tk root widget, which is a window with a title bar that contains a close icon (x), minimize icon (-), and maximize icon.

When you complete step 2), you will see a small window on your desktop with the icons ‘x’ for closing the window, ‘-‘ for minimizing the window, and ﬦ icon for maximizing the window.  The window will look like the image below.

Canvas Widget Create a Canvas
Create a Canvas to Draw Shapes on

The coordinates used in the Canvas are as indicated on the image. Let us assume the canvas size is 200×200. That is 200 pixels in the x-direction (going from left to right) and 200 pixels in the y-direction (going from top to bottom.)

Let us suppose you want to create a canvas object and name is “canvasX”.

The syntax to create a Canvas object called “canvasX” is as in the statement below. This statement will return a new Canvas widget.

    canvasX = tk.Canvas(parent, option=value, ...)

The canvasX object is a blank Canvas widget.

In the following sections, we will create different object using the Canvas class.

Canvas Widget Objects

Canvas widget class has many objects. In the sections below, we will write programs using the following Canvas widget objects:

  • Canvas Line object
  • Canvas Rectangle object
  • Canvas Oval object
  • Canvas Circle object
  • Canvas Polygon object

Line Objects (Method create_line)

Canvas widget line objects are created by the create_line method that draws a line between two points. 

To create a line on canvas named “canvasX”, use the create_line method as below.

>>> canvasX.create_line(x1, y1, x2, y2)

“canvasX” is the Canvas name. You can choose any name you like.

x1, y1 are coordinates of the first point and x2, y2 are the coordinates of the end-point of the line.

PROGRAM EXAMPLE: CANVAS create_line METHOD
>>> from tkinter import *			# 1)
>>> root = Tk()					# 2)
>>> canvas_width = 200				# 3)
>>> canvas_height = 200
>>> # Create an instance of Canvas class 
>>> # and name the instance 'canvasX'.
>>> canvasX = Canvas(root, width = canvas_width,
 height = canvas_height)	                # 4)
>>> canvasX.pack()				# 5)
>>> canvasX.create_line(10,10, 190, 190)	# 6)
1						# 7)
>>>

Detailed Line-by-line Explanation of the Program:

  1. from tkinter import *. As explained above.
  2. root = Tk() As explained above.
  3. Define variables (canvas_width and canvas_height and assign values = 200 pixels)
  4. canvasX = Canvas(root, width = canvas_width, height = canvas_height)
    • Create an instance of the Canvas class with width = canvas_width and height = canvas_height and give it a name of your choice.  In this example, we named it ‘canvasX’.
    • There are parameters within the parenthesis.  The first parameter must be the parent widget. In this case, the parent is the “root” that we created in step 2). 
    • This statement makes the instance “canvasX” a child of class “root” (parent).
  5. canvasX.pack() Use pack() method on object ‘canvasX’.
  6. canvasX.create_line(10,10, 190, 190)
    • Use method create_line on object “canvassX”.
    • Note the four parameters (10, 10, 190, 190). The first two parameters 10, 10 are the (x,y) coordinates of the point 1 (start of the line). These coordinates are referred to as (x1,y1). The last two parameters (190,190) are the (x,y) coordinates of point 2 (the end of the line). These coordinates are called (x2,y2). Create_line method draws the line between points (10,10) and (190,190).

Below is the program output.

Canvas Widget Draw a line
Line Object create_line Method

In step 7) of the program,

Note the number ’1’ on the last line (step 7). This is the number that is returned by the program and is called an identifier. When we use any method such as create_line, create_rectangle, etc., the program returns a number called identifier (in the above program, it is ‘1’). This identifier will be different every time you run the program again and again in the same window. We will have further use of this identifier in programs that we will develop later in this chapter. Let us modify the above program to save this identifier in a variable, so we can use it as we develop more programs.

We will modify the statement in step 6) to store the identifier returned by the program in a variable named “identifier1”. 

In the program below “identifier1” stores the identifier returned by the program.

PROGRAM EXAMPLE: CANVAS create_line METHOD WITH IDENTIFIER VARIABLE
>>> from tkinter import *                      # 1)
>>> root = Tk()                                # 2)
>>> # Define variables that store 
>>> # the width and height of the container.   # 3)
>>> canvas_width = 200
>>> canvas_height = 200
>>> # Create an instance of Canvas class 
>>> # and name the instance 'canvasX'          # 4)
>>> canvasX = Canvas(root, width = canvas_width, height = canvas_height)      
>>> canvasX.pack()                             # 5)
>>> identifier1 = canvasX.create_line(10,10, 190, 190) # 6)
>>>

Detailed Explanation of the Program

Step 1) and step 5) are the same as explained in the create_line Program Example in the previous section,

Step 6): identifier1 = canvasX.create_line(10,10, 190, 190)

Use canvas widget create_line method on object ‘canvasX’ and store the identifier returned by the program in a variable named “identifier1”. The first two parameters (10,10) are the (x,y) coordinates of point 1 (start of the line). The last two parameters (190,190) are the (x,y) coordinates of point 2 (the end of the line). create_line method draws the line between points (10,10) and (190,190).

Rectangle Objects (Method create_rectangle)

Canvas widget rectangle objects are created by the create_rectangle method.  Create_rectangle() method requires the specification of the coordinates of the top-left corner (x1,y1) and the bottom-right corner (x2, y2) of the rectangle (the two opposite corners).

To create a rectangle object on canvas ‘canvasX’, use the create_rectangle method as in the statement below.

>>> canvasX.create_rectangle(x1,y1,x2,y2, options)

Where ‘canvasX’ is the name of the Canvas on which the rectangle will be drawn. x1, y1 are the coordinates of the top-left corner of the rectangle, and x2, y2 are the coordinates of the bottom-right corner of the rectangle.

There are many options available for Create_rectangle() method.  In our example programs, we will use only fill=’ ‘, width= ‘  ‘, and outline=’  ‘ options.

Canvas_rectangle Options

OPTIONDESCRIPTION
fillThe default fill is a blank rectangle.  You can fill the
interior of the rectangle by using option fill = ‘color’.
WidthSpecifies the width of the border. Default is 1 pixel.
If you use width=0, the border becomes invisible.
OutlineSpecifies the color of the border.
Default is outline=’black’.
Create_rectangle Options

We will use the random() module to select the coordinates for the rectangle’s corners instead of specifying two fixed coordinates in the program below.

The result is that if you run this program several times, Tkinter will draw rectangles of different widths and heights each time by randomly selecting (x1, y1) and (x2, y2) using the random() module.

Refer back to the Python Modules chapter. You will see that the random() module can be used to generate a random number between two specified numbers. For example, the statement

x1 = random.randrange (1,10)

generates a random number in the range between 1 and 10.

The following program uses canvas widget create_rectangle() method to create a rectangle object.

PROGRAM EXAMPLE: Canvas Widget – create_rectangle Method USE EXAMPLE
>>> from tkinter import *                      # 1
>>> import random                              # 1a
>>> root = Tk()                                # 2
>>> canvas_width = 200                         # 3
>>> canvas_height = 200 
>>> canvasX = Canvas(root, width = canvas_width, height = canvas_height) # 4
>>> canvasX.pack()                             # 5
>>> x1 = random.randrange(1,10)                # 6
>>> y1 = random.randrange(1,10)                # 6a
>>> # Lower right corner of the rectangle 
>>> # coordinates (x2,y2) greater than (x1,y1)
>>> x2 = x1 + random.randrange(10, 100)        # 7
>>> y2 = x2 + random.randrange(10, 100)        # 7a
>>> identifier1 = canvasX.create_rectangle(x1,y1,x2,y2)  # 8
>>>

Detailes Lin-by-line Explanation of the Program

Step 1 through Step 5 are the same as in create_line programs.

Step 1a): import random

We import the random() module.  The random module has a function called randrange() that generates random numbers for the top-left corner coordinates (x1,y1) and bottom-right corner of the rectangle coordinates (x2,y2). 

We will get rectangles of different widths and heights each time we run this program because the randrange() function generates a different number for the rectangle’s width and height each time you run it.

6):  x1 = random.randrange(1,10).

6a): y1 = random.randrange(1,10)

In Steps 6) and 6a), we use the random() module’s randrange() method to generate a random number between 1 and 10 for the coordinates (x1,y1) of the top-left corner of the rectangle.

7): x2 = x1 + random.randrange(10, 100)

7a): y2 = x2 + random.randrange(10, 100)

In steps 7) and 7a), two random numbers are generated for coordinates (x2, y2) for the bottom-right corner of the rectangle.

We would like the bottom-right corner coordinates to be larger than the top-left corner coordinates (x1,y1).

Therefore, the coordinate x2 is created by adding the generated random number to x1.  Similarly, y2 is created by adding the generated random number to y1.

Step 8): identifier1 = canvasX.create_rectangle(x1,y1,x2,y2).

The create_rectangle method draws a rectangle between diagonally opposite corners (x1,y1) and (x2,y2) and saves the identifier returned by the program in the variable ‘identifier1’.

Try running this program repeatedly a few times.  You will see that the rectangle dimensions are different every time. Below is the rectangle generated by the program.

Tkinter Canvas Widget create_rectangle Method
Canvas Rectangle Object create_rectangle Method

Canvas Widget: create_rectangle with Color Fill

Now let’s use the canvas widget create_rectangle options fill=’ ‘, width= ‘  ‘, and outline=’  ‘, described in the table above.

The program below is the same as the previous program. The only difference is that it uses the options fill color = ’RED’, outline width = 5, and outline color = ‘BLUE’.

PROGRAM EXAMPLE: create_rectangle WITH COLOR FILL
from tkinter import *
import random
root = Tk()
canvas_width = 200
canvas_height = 200
canvasX = Canvas(root, width = canvas_width, height = canvas_height)
canvasX.pack()
x1 = random.randrange(10,20)
y1 = random.randrange(10, 20)
x2 = x1 + random.randrange(20, 180)
y2 = y1 + random.randrange(20, 180)
identifier1 = canvasX.create_rectangle(x1,y1,x2,y2,
 fill = 'RED', outline = 'BLUE', width = 5)

Below is the program output:

Canvas Widget create_rectangle with Color Fill
Canvas Rectangle Object create_rectangle Method and Color Fill

Oval and Circle Objects

As discussed in Math Applications, the circle is a curve that has every point on the curve the same distance away from the center denoted by point ‘C’.  This distance is called the radius, denoted by the symbol ‘R’.

An oval can be thought of as a squished circle.  If it is squished horizontally (in the x-direction), it becomes tall and narrow.  If it is squished vertically (in the y-direction), it becomes long and less tall.

Tkinter canvas widget has a method create_oval() that draws circles and ovals. The create_oval method requires that we specify the coordinates of two corners of a rectangle (top-left and bottom-right) within which the circle or the oval can be inscribed. If the two corner coordinates define a rectangle, then create_oval will draw an oval.  On the other hand, if the two corner coordinates define a square, then, the create_oval method will draw a circle. 

The following statement

ovalX = C.create_oval(x1, y1, x2, y2, option1, option2...)

returns the object “ovalX” on canvas named “C” inscribed in the rectangle whose opposite corners are at (x1,y1) and (x2,y2).

Create_oval has several options similar to create_rectangle options. Some of the options are fill color, outline width, and outline color.

PROGRAM EXAMPLE: CANVAS create_oval() Method TO DRAW CIRCLE

The canvas widget program below draws a circle of radius = 50 with its center at (100,100) using fill, width, and outline options.

>>> from tkinter import *			# 1
>>> root = Tk()					# 2
>>> canvas_width = 200				# 3
>>> canvas_height = 200
>>> 
>>> canvasX = Canvas(root, width = canvas_width, 
height = canvas_height)	                        # 4
>>> canvasX.pack()				# 5
>>> radius = 50					# 6
>>> center = 100				# 6a
>>> x1 = center – radius			# 7
>>> y1 = center – radius			# 7a
>>> x2 = y2 = center + radius			# 7b
>>> ID = canvasX.create_oval(x1,y1,x2,y2, 
fill='YELLOW', outline='RED', width=5)	        # 8 
>>> 

The following is the program result.

Canvas Wuidget create_oval Mehhod Using Color Fill and Outline Width Oprions.
Canvas Oval Object create_oval Method Using Color Fill, and Outline Width Options.

Detailed Line-by-line Program Explanation of Canvas Widget create_oval() Method with Fill Option

Steps 1 through 5) are the same as in the Canvas create_rextangle program above.

Step 6) and 6a): radius = 50 and center = 100.

Define the center and the radius of the circle.

Steps 7), 7a), and 7b): x1 = center – radius; y1 = center – radius; x2 = y2 = center + radius.

Calculate the coordinates of the top-left and the bottom-right corners of the rectangle that contains the circle.

Step 8): ID = canvasX.create_oval(x1,y1,x2,y2, fill='YELLOW', outline='RED', width=5.

Create_oval method creates an oval object on object “canvasX” bounded by the top-left corner at (100-50, 100-50), which is (50,50), and the bottom-right corner at (100+50, 100+50), which is (150,150).  The identifier returned by Python is saved in the variable ‘ID’.

This statement fills the circle with yellow color. The outline of the circle is red. The statement selects the width of the outline = 5 pixels.

We drew a circle using create_oval method above. Now, let us draw an oval using create_oval method.

The program below is similar to the program for drawing a circle, except (x1, y1, x2, y2) coordinates define a rectangle instead of a circle.

PROGRAM EXAMPLE: CANVAS create_oval() METHOD TO DRAW AN OVAL
>>> from tkinter import *			# 1	
>>> root = Tk()					# 2
>>> canvas_width = 200				# 3
>>> canvas_height = 200
>>> canvasX = Canvas(root, width = canvas_width, 
height = canvas_height)		                # 4
>>> canvasX.pack()				# 5
>>> oval_center = 100				# 6
>>> oval_x_radius = 75				# 6a
>>> oval_y_radius = 50				# 6b
>>> x1 = oval_center - oval_x_radius		# 7
>>> y1 = oval_center - oval_y_radius		# 7a
>>> x2 = oval_center + oval_x_radius		# 7b
>>> y2 = oval_center + oval_y_radius		# 7c
>>> ID = canvasX.create_oval(x1,y1,x2,y2,
fill='LIGHTBLUE', outline='RED', width=5)	# 8
>>>

The following is the program output.

Canvas Widget create_oval Method with Color Fill and Outline Width
Canvas Oval Object create_oval Method Using Color Fill, and Outline Width Options.

Detailed Line-by-line Program Explanation of Canvas Widget create-oval() Method with Fill and Outline Width Options:

Steps 1) through Step 5): Same as create_oval programs to draw circle example.

Steps 6), 6a), and 6b): Set the oval center and oval radius in the x-direction and y-direction.

Steps 7), 7a), 7b), and 7c): These statements calculate the top-left and bottom-right coordinates of the bounding rectangle that will contain the oval.

Step 8): ID = canvasX.create_oval(x1,y1,x2,y2,fill='LIGHTBLUE', outline='RED', width=5)

Create_oval method creates an oval object on object “canvasX” bounded by the top-left corner (100-75, 100-50), which is (25,50), and the bottom-right corner at (100+75,100+50), which is (175,150) of the bounding rectangle.  The identifier returned by Python is saved in the variable ‘ID’.

create_polygon Method

Tkinter canvas widget can be used to draw polygons of any number of sides. Whereas for create_rectangle, we provide coordinates of the two opposite corners of the rectangle, for polygons we need to provide coordinates of each of the corners of the polygon.

The create_polygon program uses the same statements as the previous programs.

The following statement is used in place of statement 8). This statement will draw a polygon with five sides.

>>> id1 = canvasX.create_polygon(x1,y1,x2,y2, x3,y3, x4,y4,x5,y5)

Verified by MonsterInsights