Animation is a vast field. Countless animation software are available to create very impressive 2D and 3D animations. Python can also be used to create small animation program to understand the functions of graphics.py. In this post we will create a small Python Graphics Animation of growing circles.
The program starts with a growing circle at the center of the drawing area. When you double click at any point within the drawing area a new circle will start growing at the clicked location. The circle is filled with a randomly selected color from the color array declared at the beginning of the program.
Python Graphics Animation- coding the growing circles program
The program uses the random, time and graphics module. Random module is use to add the delay to create animated effect using the sleep function of time module.
GraphWin – class is used to create a graphics windows object to create a drawing area.
Text – class is used to create the text object to print the text message on the drawing area.
Circle– class is used to create the circle object to create a circle at the point specified in first argument
checkMouse- method is used with GraphWin object to check if the mouse has been clicked by user. This is used to stop the growing circle.
getMouse- method is used with GraphWin object to get the position where the mouse has been clicked by user. This is used to define the center point of the new circle.
setOutline- method is used with Circle object to define the color of the outline of the circle.
setFill- method is used with Circle object to define the color to fill in the circle.
sleep- method is used with Time object to add the delay in the while loop used for drawing the growing circle.
randrange– method is used with random object to generate an integer to randomly select a color from the col_arr.
import random import time from graphics import * def main(): workArea = GraphWin('Growing Circles', 400, 400) # give title and dimensions col_arr=["violet","indigo","blue","green", "yellow","orange","red","pink", "brown","purple","gray","maroon", "black","lime","cyan","thistle", "orchid","tomato","gold","aqua", "fuchsia","navy","plum","crimson", "lightcoral","royalblue", "deeppink"] msg=Text(Point(150,10),"Double Click to Start a new circle") msg.draw(workArea) i=1 x=workArea.width/2 y=workArea.height/2 clk=True while clk: rad=20 #get a color from colors array clr=col_arr[random.randrange(len(col_arr))] #let the circle grow unless you double click while not workArea.checkMouse(): cir=Circle(Point(x,y),rad) cir.setFill(clr) cir.setOutline(clr) cir.draw(workArea) #increment radius rad=rad+1 #add delay time.sleep(0.08) msg=Text(Point(150,10),"Double Click to Start a new circle") msg.draw(workArea) # redefine center of circle where you click ch=workArea.getMouse() x=ch.x y=ch.y workArea.getMouse() workArea.close() # close the workArea window main()