Python Graphics programming makes you understand how to use basic graphics function to create simple drawings. It can be fun while learning the basic elements and techniques of Python Graphics.
John Zelle created this simple graphics module for use with his Python Programming book. The class GraphWIng and a whole set of methods available in this module can be found here.
To use the methods in graphics.py you have to import it in every Python Graphics program you create. Graphics.py is not a component standard Python distribution. It can be copied from here and saved as graphics.py in the folder where you will save your Python Graphics programs.
Any Python Graphics program will require these four tasks
- Import graphics.py
- Create a GraphWin Object
- Paint the output of graphics functions on the declared window object
- Close the opened GraphWin Object
Import graphics.py
You need to write this at the top of your code to import graphics.py.
from graphics import *
Create a GraphWin Object
The next thing is to create a window area where the output of Python Graphics program will be displayed. It is created like this
Window_object= GraphWin(text-title, width, height)
displayArea=GraphWin('Rainbow Circle', 300, 300)
In the second code line the window object is identified by WorkArea. It is an instance of GraphWin class defined in graphics.py. It draws a toplevel window to display the output. This opens a window with title “Rainbow Circle” and the size is 300 X300 pixels.
Paint Output Graphics Functions in Declared Window Object
After creating the GraphWin Object you can use the graphics functions from graphics.py to create your basic graphics images. Output of the graphics functions are displayed with draw method. It is called with the shape object to be displayed and passing GraphWin object as parameter.
cir= Circle(Point(100,100), 20) cir.draw(displayArea)
This code will draw a circle of radius 20 pixels at center 100,100
Close the GraphWin Object
This is the last part of any Python Graphics program. Close method is called to close the declared GraphWin object and free the resources.
diaplayArea.close()
Program Example
Draw concentric circles using the rainbow colors
from graphics import * def main(): col_arr=["violet","indigo","blue","green","yellow","orange","red"] workArea = GraphWin('Rainbow Circle', 300, 300) # give title and dimensions x=workArea.getWidth()/2 # get x of middle of drawing area y=workArea.getHeight()/2 # get y of middle of drawing area i=0 while i<len(col_arr): cir=Circle(Point(x, y), 10+10*i)# draw circle with center at middle of drawing area cir.setOutline(col_arr[i]) #get a next outline color from color array cir.setWidth(4)#set outline width cir.draw(workArea)#draw the current circle i+=1 # increment counter for iteration message = Text(Point(workArea.getWidth()/2, 250), 'Click to Exit') message.draw(workArea) workArea.getMouse()# get mouse to click on screen to exit workArea.close() # close the drawing window main()