Canvas Widget

Animation Using Canvas.move() Function

So far, we have done graphics programming that draws static shapes that do not move. Graphics programming to enable the images to move is called animation.

You may have played games on XBOX or Sony PlayStation.  The objects in these games move very fast and are action-packed. The programs in this section will make the images move, not as fast as in an XBOX or Playstation, but slowly. Such programs will give you a glimpse into graphics programming.

Tkinter canvas widget has a canvas.move function that can move the objects you have drawn using the techniques we learned in the previous sections. We will start with the (x,y) coordinates of the image and will add the amounts we want to move the image by to the (x,y) coordinates.

Canvas.move function syntax

Canvas.move(Indentifier, x-direction move, y-direction move)

Identifier: Recall that the canvas_create function returns an identifier. We saved the Identifier as the variable “ID” in the programs in the previous section.

x-direction move” specifies the value by which you would like to move the image in the x-direction.

y-direction move” specifies the value by which you would like to move the image in the y-direction.

For example, canvas.move(ID, 0, 5) will move the image by zero pixels in the x-direction and 5 pixels in the y-direction. Similarly, canvas.move(ID, 5, 0) will move the image 5 pixels in the x-direction and zero pixels in the y-direction. Finally, canvas.move(ID, 5, 5) will move the image 5 pixels in both the x-direction and y-direction.

Canvas update() Function

The canvas class has a function to help in our animation applications.  This function is called update()

This update() function updates the screen to show the new position of the image after every move as specified in the canvas.move(ID, x, y) statement. 

It is necessary to update the screen after each move of the image. If an update is not done, the object will jump to the final location without gradually moving through intermediate positions on the screen.

Python time Module’s sleep() Function

Finally, for the animation applications, we need module time()

The Python time module has a function called sleep().  The animation programs will use the function time.sleep().

Sleep() function was discussed in the Python Modules chapter. The value within the parenthesis of time.sleep() function is the number of seconds we want Python to stay idle. Python sleeps for this duration.

So, if we type time.sleep(0.10), the program will sleep for 1/10th of a second after every move specified in canvas.move(ID, x, y) statement. 

Thus, the statement canvas.move(ID, x, y) followed by time.sleep(0.10) statement will make Python sleep for 1/10 of a second after moving the image x pixels in the x-direction and y pixels in the y-direction.

In our program, we will put the canvas.move(x,y), update(), and time.sleep() statements in a loop so the image will move a specified number of pixels, update the screen with the image in the new position, sleep for a specified time, and then go back to the top of the loop and repeat the move, update the screen, and sleep.  This sequence will repeat until the loop is exhausted.

Let us explain the above more clearly with a program example. 

Animation: Moving a Ball To The Right

In the program below, at the start of the program, the ball is positioned at the top-left corner of a 500×500 canvas.

Step 6) of the program: the for statement:

The for statement implements a loop that repeats 50 times. For each iteration of the loop, the ball moves 5 pixels to the right (x-direction). It then updates the screen to show the ball’s new position. Python then waits for 1/10th of a second.

The program branches to the top of the for loop and repeats the statement in the for loop again. This process repeats 50 times. 

If you run this program, you will see the red ball move to the right.

PROGRAM EXAMPLE: canvas.move() ANIMATION

Program Name: tkinter_canvas.move_animation.py

>>> from tkinter import *			#1
>>> import time					#1a
>>> root = Tk()					#2
>>> canvasX = Canvas(root, width = 500, height = 500)	#3
>>> canvasX.pack()				#4
>>> ID = canvasX.create_oval(20,20,50,50, fill = 'red')	#5
>>> for x in range(0,50):			#6
	canvasX.move(ID, 5,0)			#7
	root.update()
	time.sleep(0.1)

Below is the program animation output.

Canvas.move() animation

Detailed Line-by-line Explanation of the Program:

  1. from tkinter import * This step is the same as with all Tkinter programs. Step 1a): import time
    • We import the python time module. 
    • The time module is used in step 7) to specify the amount of time the program will sleep.
  2. root = Tk()
    • This step is the same as in all Tkinter programs
  3. canvasX = Canvas(root, width = 500, height = 500)
    • In this step, we create an instance of the widget Canvas. 
    • The canvas width and height are specified as 500 pixels. The object instance name is canvasX.
  4. canvasX.pack()
    • Use the pack() method on object “canvasX”.
  5. ID = canvasX.create_oval(20,20,50,50, fill = 'red')
    • Use the create_oval method on object “canvassX” to draw a circle of diameter 30.
    • The statement specifies four parameters (20, 20, 50, 50).
    • The first two parameters (20, 20) are the coordinates of the top-left corner of the square that encloses the circle.
    • The last two parameters (50, 50) are the coordinates of the bottom-right corner of the square.
  6. for x in range(0,50):
    • This step sets up a loop that uses the counting variable “x” and loops through all instructions in step 7) fifty times.
  7. canvasX.move(ID, 5,0)

     root.update()

     time.sleep(0.1)

  • In step 7, the program loops through instructions move(5, 0), screen update, and sleep for 1/10th of a second between each move of the ball.
  • The ball moves 5 pixels in the x-direction in each iteration before sleeping for 0.1 seconds.

Animation: Moving A Ball Up and Down

Let us take the next step and make the ball bounce up and down on the canvas window 100 times. The program is similar to the previous program.  In this case, we start the ball at the bottom middle of the canvas 500 x 500 pixels at coordinates (230,230).

The program uses a loop within a loop with for-range statements.  These are called the inner loop and the outer loop.

Inner Loop:

The inner loop uses the counting variable “x” that counts from 0 to 20. The inner loop repeats 20 times.

The inner loop moves the ball 5 pixels in the y-direction in each loop. 

The number of pixels to move in each loop is defined by the variable “z”. The variable “z” is assigned a value of 5 in the step 6) statement.

Outer Loop:

After the inner loop finishes 20 loops, the program sets the variable “z” to -5.

The program control then goes to the top of the program and executes the outer loop using the counting variable “y”.  Since “z” is negative, the ball will move down.

The outer loop executes 50 times, meaning the ball will move up and down 50 times.  Try this program on your computer and watch the ball go up and down.

PROGRAM EXAMPLE: canvas.move (x, y) ANIMATION UP AND DOWN

Program Name: tkinter_canvas.move_animation_up_down.py

from tkinter import *				#1
import time					#1a
root = Tk()					#2
canvasX = Canvas(root, width = 500, height = 500) #3
canvasX.pack()					#4
ID = canvasX.create_oval(230,230,250,250, fill = 'red')	#5
z = 5						#6
for y in range(1,50):				#7
    for x in range(0,20):			#8
        canvasX.move(ID,0,z)
        root.update()
        time.sleep(0.05)
    z = -z		                        #9

Below is the program output showing the animation.

Canvas.move() Animation Up/Down

Detailed Line-by-line Explanation of the Program

Steps 1) through 5) are identical to the Canvas.move() program in the previous section.

Step 6): z = 5 Define a variable “z”, which is the number of pixels to move in each inner loop.

Step 7): for y in range(1,50):

This is the outer loop.  It repeats 50 times.

Step 8):

for x in range(0,20):			#8
        canvasX.move(ID,0,z)
        root.update()
        time.sleep(0.05)

Step 8) is the inner loop.  It loops 20 times.

The canvasX.move(ID,0,z) statement moves the ball by 5 pixels. The variable “z” has a value of 5 stored in it.

The statement root.update() updates the position of the ball after each move.

The statement time.sleep(0.05) then sleeps for 5/100 seconds.

The program starts the next iteration of the inner loop after the sleep period.

This process is repeated until all 20 inner loops are exhausted.

These statements are similar to those in the example program canvas.move ANIMATION in the previous section

Step 9): z = -z

This statement reverses the direction of the ball at the end of each inner loop. Therefore, the ball goes down in the next outer loop. In successive outer loops, the ball reverses its direction.

Canvas.move() Using Class Structure

The following program illustrates the of use class structure to write canvas.move(x,y) program.  This program executes the loop 25 times moving the ball 5 pixels in each loop in the +x direction. The count variable in this loop is “x”.

Then, the program executes another for-range() loop using the count variable “y” and moves the ball 5 pixels in each loop in the +y direction.  This loop loops 25 times.

Then, the program executes another for-range() loop using the count variable “z”.  It loops 25 times and moves the ball 5 pixels in each loop in the negative x-direction.

Finally, the program executes another for-range loop using the count variable “w”. It moves the ball up (+y direction) 5 pixels in each loop.

PROGRAM EXAMPLE: canvas.move() CLASS STRUCTURE

Program name: tkinter_canvas.move_animation_class_structure.py

# This program uses canvas.move() function to move a ball
# using class structure
from tkinter import *				#1
import time					#1a
root = Tk()					#2
class moveBall:					#3
    def __init__(self, root):			#4
        self.canvasX = Canvas(root, width = 500, height = 500) 	#5
        self.canvasX.pack()			#6
        Id = self.canvasX.create_oval(50, 50, 100, 100, 
fill = 'RED')                                   #7
        for x in range(0,25):			#8
            self.canvasX.move(Id, 5, 0)
            root.update()
            time.sleep(0.1)
        for y in range(0, 25):			#9
            self.canvasX.move(Id, 0, 5)
            root.update()
            time.sleep(0.1)
        for z in range(0, 25):			#10
            self.canvasX.move(Id, -5, 0)
            root.update()
            time.sleep(0.1)
        for w in range(0, 25):                  #11 move up
            self.canvasX.move(Id, 0, -5)
            root.update()
            time.sleep(0.1)

testmoveBall= moveBall(root)		        #12
root.mainloop()                                 #13

Below is the program output.

Canvas.move() Animation Class Structure

Detailed Line-by-line Program Explanation of the Program

  1. Step 1) and 1a) are the same as in program Example canvas.move(x,y) Animation Up and Down.
  2. Step 2) is the same as in program Example canvas.move(x,y) Animation Up and Down.
  3. class moveBall:
  4. def __init__(self, root):
    • __init__   This initializer method (__init__) is followed by two class attributes (self and root). This method defines what GUI should do.
  5. self.canvasX = Canvas(root, width = 500, height = 500)
    • Create an instance of the Canvas class, named “canvasX”, which is 500 pixels wide and 500 pixels high.
  6. self.canvasX.pack()
    • Run the pack() method on object “canvasX”. 
    • The pack method adjusts the canvas instance to the size defined above step 5).
  7. Id = self.canvasX.create_oval(50, 50, 100, 100, fill = 'RED')
    • Create an oval image with red fill and store the identifier in the variable “ID”.
  8. for x in range(0,25):
    • Operate the create_move() method on object “canvasX” and loop through the for-range loop to move the ball in the +x direction.
  9. for y in range(0, 25):
    • Operate the create_move() method on object “canvasX” and loop through the for-range loop to move the ball in the +y direction.
  10. for x in range(0,25):
    • Operate the create_move() method on object “canvasX” and loop through the for-range loop to move the ball in the -x direction.
  11. for y in range(0, 25):
    • Operate the create_move() method on object “canvasX” and loop through the for-range loop to move the ball in the -y direction.
  12. testmoveBall= moveBall(root)
    • This step creates an instance of the class “moveBall”. The instance is named “testmoveBall”.
  13. root.mainloop()
    • In the last step, we run the method “mainloop” on the object “root” to run the application, we just wrote.

Copyright © 2019 – 2021 softwareprogramming4kids.com

All Rights Reserved

Verified by MonsterInsights