Canvas Widget

Canvas Draw Using Class Structure

The previous Canvas widget program examples used procedural programming to focus solely on Tkinter concepts.

Now, we will write a few programs using class structure programming by wrapping our code in classes.

The structured programming concepts and modules were presented in Object Oriented Programming chapter.

The program below draws a circle using the create_oval method using structured programming concepts.

As mentioned earlier, the advantage of using classes is that the application becomes structured and is easier to understand and debug, especially when the programs become big and complex.

In larger programs, it is advisable to divide the application into classes. In our case, the program is very small, so there is no need to use classes.  Nonetheless, this exercise illustrates how to do application programming to structure the program by using classes.

create_oval Method Using Class Stucture

The canvas widget program below generates a circle inscribed in a square with top-left corner (50,50) and bottom-right corner coordinates (150,150).

PROGRAM EXAMPLE: create_oval METHOD STRUCTURED PROGRAMMING
>>> from tkinter import *			# 1
>>> root = Tk()					# 2
>>> class oval:					# 3
	def __init__(self,root):		# 4
		self.canvasWidth = 200		# 5
		self.canvasHeight = 200		# 5a
		self.canvasX = Canvas(root, width =
 self.canvasWidth, height = self.canvasHeight)  # 6
		self.canvasX.pack()		# 7
		ID=self.canvasX.create_oval(50,50,150,150,
 fill='ORANGE',outline='BLUE',width =10)        # 8
		return				

>>> testOvalApp = oval(root)			# 9
>>> root.mainloop()                             #10

Detailed Line-by-line Explanation of the Program:

  1. from tkinter import * This step is the same as in all Tkinter programs.
  2. root = Tk() This step is the same as in all Tkinter programs.
  3. class oval:
    • Create a class called “oval” and a method __init__ that we learned in the Object-Oriented Programming chapter. We will create an instance of the ‘oval’ class in step 9) and run the app in step 10).
  4. def __init__(self,root):
    • The initializer method (__init__) has two class attributes (“self” and “root”).
    • This defines a method for what GUI should do.
  5. Steps 5) and 5a)
    • self.canvasWidth = 200 and self.canvasHeight = 200
    • Before creating an instance of the Canvas class in step 6), define two variables “canvasWidth” and “canvasHeight” and assign values of 200 pixels for width and 200 pixels for the height of the canvas.
  6. self.canvasX = Canvas(root, width = self.canvasWidth, height = self.canvasHeight)
    • This step instantiates a class instance named “canvasX”.
  7. self.canvasX.pack()
    • Use the pack() method on object “canvasX”.  The pack() method makes the canvas instance to the size defined in step 5) above
  8. ID = self.canvasX.create_oval(50,50,150,150, fill='ORANGE', outline='BLUE', width = 10)
    • Operate the create_oval method on object “canvasX”.
    • Store the identifier returned by the program in the variable named ‘ID’.
  9. testOvalApp = oval(root)
    • This step creates an instance of the class “oval”. The instance is named “testOvalApp”.
  10. root.mainloop()
    • Last step, we run the method “mainloop” on object “root” to run our application, we just wrote.
    • mainloop() is an infinite loop that continues to run the application

The program output is show below:

Canvas Widget create_oval method with color fill and thick outline.
Canvas Oval Object create_oval Method Using Color Fill, and Outline Width Options Class Structure

Canvas Line and Oval Together

Let’s now combine what we have learned about the Canvas class.

The canvas widget program example low combines the oval and line and a lot of colors. It creates a flower bouquet for a birthday party using the create_oval and create_line methods.

PROGRAM EXAMPLE: CANVAS create_line AND create_oval TOGETHER
>>> from tkinter import *
>>> root = Tk()
>>> canvasX = Canvas(root, width = 300, height = 300)
>>> canvasX.pack()
>>> ID = canvasX.create_oval(20,70,70,120, fill = "red")
>>> ID1 = canvasX.create_oval(60,30,110,80, fill = "yellow")
>>> ID2 = canvasX.create_oval(100,60,150,110, fill = "blue")
>>> ID3 = canvasX.create_oval(140,80,190,130, 
fill = "lightgreen")
>>> ID4 = canvasX.create_oval(180,50,230,100, 
fill = "orange")
>>> ID4 = canvasX.create_line(125,250,45,120)
>>> ID5 = canvasX.create_line(125,250,85,80)
>>> ID6 = canvasX.create_line(125,250,125,110)
>>> ID7 = canvasX.create_line(125,250,165,130)
>>> ID8 = canvasX.create_line(125,250,205,100)
>>> root.mainloop()

The program uses the “fill” option to fill the colors in the balloons.

Refer to the Enrichment: More About Colors section in the Pygame Drawing and Animation chapter for the theory of colors.

You can create any custom color by specifying the values of the ‘RED’, ‘GREEN’, and ‘BLUE’ (RGB) colors. The R, G, and B colors can have a value from 0 to 255.  By choosing any number between 0 and 255 for the R, G, and B colors, any custom color can be created.

Tkinter recognizes color names in the Table below. 

Color Names Supported by Tkinter

Fill=’color’
‘red’
‘green’
‘blue’
‘orange’
‘yellow’
‘pink’
‘magenta’
‘purple’
‘cyan’
‘violet’
Color Names Supported by Tkinter
Tkinter Canvas Widget
Canvas Oval Object and Line Object create_oval and create_line Methods Using Color Fill, and Outline Width Options

How to Add Text to a Canvas (create_text Method)

How about we add some text to our balloon bouquet?  Let us learn how to add text to Canvas. You can display one or more lines of text on a Canvas canvasX by creating a text object:

    Txt1 = canvasX.create_text(x, y, option, ...)

This statement returns a text object named “txt1” on Canvas named “canvasX“.

To write text to the canvas, we need to specify the (x,y) coordinates of the starting point where the text should start from.  

The create_text method lets you specify the options such as the text color, font type, font size (points), and font face (normal, bold, italics).  The default font face is “normal”.

The canvas widget program below uses the following two options. It uses the font option to write “Happy Birthday!! BEST WISHES!!”.

OPTIONDESCRIPTION
FillThe default text color is a black,
but you can set any color using option fill = ‘color’.
FontChange the font type, size, and weight
by using the tuple font = (‘font type’, size, weight),
where size is the height of the font in points,
weight = ‘normal’, or ‘bold’
Canvas Text Options
PROGRAM EXAMPLE: CANVAS create_text USE EXAMPLE
>>> from tkinter import *
>>> root = Tk()
>>> canvasX = Canvas(root, width = 300, height = 300)
>>> canvasX.pack()
>>> ID = canvasX.create_oval(20,70,70,120, fill = "red")
>>> ID1 = canvasX.create_oval(60,30,110,80, fill = "yellow")
>>> ID2 = canvasX.create_oval(100,60,150,110, fill = "blue")
>>> ID3 = canvasX.create_oval(140,80,190,130, 
fill = "lightgreen")
>>> ID4 = canvasX.create_oval(180,50,230,100, 
fill = "orange")
>>> ID4 = canvasX.create_line(125,250,45,120)
>>> ID5 = canvasX.create_line(125,250,85,80)
>>> ID6 = canvasX.create_line(125,250,125,110)
>>> ID7 = canvasX.create_line(125,250,165,130)
>>> ID8 = canvasX.create_line(125,250,205,100)
>>> ID9 = canvasX.create_text(135,250, text = 
'Happy Birthday!!', fill = 'purple', 
font = ('verdana', 16))
>>> ID10 = canvasX.create_text(135,280, 
text = 'BEST WISHES!!', fill = 'orange', 
font = ('calibri', 24))
>>> root.mainloop()

This program creates the image below.

Canvas Widget
Canvas Oval Object and Line Object create_oval and create_line create_text Methods Using Color Fill, and Outline Width Options
Verified by MonsterInsights