struct the oval.
Example:
cornerPoint = an0val . getP1 ( )1 17
Polygon Methods
Polygon (point 1 , point2 , point3 , . .
. ) Constructs a polygon with the given points as vertices. Also accepts a single parameter that is a list of the vertices.
Example:
aPolygon - Polygon (Point ( 1 , 2) , Point (3 , 4) , Point (5 , 6) )Example:
aPolygon - Polygon ( [Point ( 1 , 2) , Point (3 , 4) , Point (5 , 6) ] ) getPoints() Returns a list containing clones of the points used to construct the
polygon.
Example:
pointList = aPolygon . getPoints ( )Text Methods
Text (anchorPoint , text String)
Constructs a text object that displays
text Stringcentered at
anchorPoint.The text is displayed horizontally.
Example:
message = Text (Point (3 , 4) , "Hello ! " ) setText ( string)Sets the text of the object to
string.Example:
message . set Text ( " Goodbye ! " ) get Text ( )Returns the current string.
Example:
msgString = message . getText ( ) getAnchor ( )Returns a clone of the anchor point.
Example:
centerPoint = message . getAnchor ( )setFace (family)
Changes the font face to the given
family.Possible values are
"helvet ica" , " courier " , "times roman",and
" arial " .Example:
message . setFace ( " arial " )set Size (point )
Changes the font size to the given
pointsize. Sizes from 5 to 36 points are legal.
Example:
message . setSize ( 18)setStyle ( style)
Changes font to the given
style.Possible values are:
"normal " ,"bold", " italic " ,
and
"bold italic " .Example:
message . setStyle ( "bold" )4.8. Graphics Module Reference
setTextColor ( color)
Sets the color of the text to
color.Note:
setFillhas the same effect.
Example:
message . setTextColor ( "pink" )14.8.31
Entry ObjectsObjects of type
Entryare displayed as text entry boxes that can be edited by the user of the program.
Entryobjects support the generic graphics meth
ods
move 0 , draw (graphwin) , undraw 0 , setFill ( color) ,and
clone 0 .The
Entry
specific methods are given below.
1 19
Entry (centerPoint , width)
Constructs an
Entryhaving the given center point and
width.The
widthis specified in number of characters of text that can be displayed.
Example:
inputBox = Entry (Point (3 , 4) , 5)getAnchor
() Returns a clone of the point where the entry box is centered.
Example:
centerPoint = inputBox . getAnchor ( )get Text ( )
Returns the string of text that is currently in the entry box.
Example:
inputStr = inputBox . getText ( )set Text ( string)
Sets the text in the entry box to the given string.
Example:
inputBox . setText ( " 32 . 0 " )setFace (family)
Changes the font face to the given
family.Possible values are
"helvet ica" , " courier " , "times roman",and
" arial " .Example:
inputBox . setFace ( " courier " )set Size (point )
Changes the font size to the given
pointsize. Sizes from 5 to 36 points are legal.
Example:
inputBox . set Size ( 12)setStyle ( style)
Changes font to the given
style.Possible values are:
"normal " ,"bold", " italic " ,
and
"bold italic " .Example:
inputBox . setStyle ( " italic " )setTextColor ( color)
Sets the color of the text to
color.Example:
inputBox . setTextColor ( " green" )14.8.41
Displaying ImagesThe graphics module also provides minimal support for displaying and manipu
lating images in a
GraphWin.Most platforms will support at least PPM and GIF images. Display is done with an
Imageobject. Images support the generic meth
ods
move ( dx , dy) , draw (graphwin) , undraw() , and
clone ( ) .Image-specific methods are given below.
Image (anchorPoint , f ilename)
Constructs an image from contents of the given file, centered at the given anchor point. Can also be called with
widthand
height
parameters instead of
f ilename.In this case, a blank (transpar
ent) image is created of the given width and height (in pixels).
Example:
flowerimage = Image (Point ( 100 , 100) , " flower . gif " )Example:
blankimage = Image (320 , 240)getAnchor
() Returns a clone of the point where the image is centered.
Example:
centerPoint = f lowerimage . getAnchor ( ) getWidth OReturns the width of the image.
Example:
widthinPixels = flowerimage . getWidth ( ) getHeight 0Returns the height of the image.
Example:
height inPixels = flowerimage . getHeight ( )getPixel (x , y )
Returns a list
[red , green , blue]of the RGB values of the pixel at position
(x , y) .Each value is a number in the range 0-255 indi
cating the intensity of the corresponding RGB color. These numbers can be turned into a color string using the
color _rgbfunction (see next section).
Note that pixel position is relative to the image itself, not the window where the image may be drawn. The upper-left comer of the image is always pixel
( 0 , 0) .Example:
red , green , blue = f lowerimage . getPixel (32 , 18)setPixel (x , y , color)
Sets the pixel at position
(x , y)to the given color.
Note: This is a slow operation.
Example:
flowerimage . setPixel (32 , 18 , "blue " )save (filename)
Saves the image to a file. The type of the resulting file (e.g., GIF or PPM) is determined by the extension on the filename.
Example:
flower Image . save ( "mypic . ppm" )4.8. Graphics Module Reference
14.8.51
Generating ColorsColors are indicated by strings. Most normal colors such as
"red" , "purple " ," green" , " cyan" ,
etc. should be available. Many colors come in various shades, such as
" red1 " " red2 " "red3 " "red4 " ' ' ' 'which are increasingly darker shades of red. For a full list, look up
Xl lcolor names on the web.
The graphics module also provides a function for mixing your own colors nu
merically. The function
color_rgb (red , green , blue)will return a string rep
resenting a color that is a mixture of the intensities of red, green and blue spec
ified. These should be ints in the range 0-255. Thus
color _rgb (255 , 0 , 0)is a bright red, while
color _rgb ( 130 , 0 , 130)is a medium magenta.
Example:
aCircle . setFill (color _rgb ( 130 , 0 , 130) )14.8.61
Controlling Display Updates (Advanced)Usually, the visual display of a
GraphWinis updated whenever any graphics ob
ject's visible state is changed in some way. However, under some circumstances, for example when using the graphics library inside some interactive shells, it may be necessary to force the window to update in order for changes to be seen.
The
update() function is provided to do this.
update
() Causes any pending graphics operations to be carried out and the results displayed.
For efficiency reasons, it is sometimes desirable to tum off the automatic updating of a window every time one of the objects changes. For example, in an animation, you might want to change the appearance of multiple objects before showing the next "frame" of the animation. The
GraphWinconstructor includes a special extra parameter called
autoflushthat controls this automatic updating. By default,
autoflushis on when a window is created. To turn it off, the
autoflushparameter should be set to
False,like this:
win = GraphWin ( "My Animat ion" , 400 , 400 , autoflush=False)
Now changes to the objects in
winwill only be shown when the graphics system has some idle time or when the changes are forced by a call to
update ( ) .The
update ( )method also takes an optional parameter that specifies the maximum rate (per second) at which updates can happen. This is useful for controlling the speed of animations in a hardware-independent fashion. For example, placing the command
update (30)at the bottom of a loop ensures
121
that the loop will "spin" at most 30 times per second. The
updatecommand will insert an appropriate pause each time through to maintain a relatively constant rate. Of course, the rate throttling will only work when the body of the loop itself executes in less than l/30th of a second.
Example: 1000 frames at 30 frames per second
win = GraphWin ( "Update Example " , 320 , 200 , autoflush=False) for i in range ( 1000) :
# <drawing commands for ith frame>
update (30)
14.91 Chapter Summary
This chapter introduced computer graphics and object-based programming. Here is a summary of some of the important concepts:
• An
object is a computational entity that combines data and operations.
Objects know stuff and can do stuff.
Anobject's data is stored in instance variables, and its operations are called methods.
•
Every object is an instance of some class. It is the class that determines what methods an object will have.
Aninstance is created by calling a constructor method.
• An
object's attributes are accessed via dot notation. Generally computa
tions with objects are performed by calling on an object's methods. Acces
sor methods return information about the instance variables of an object.
Mutator methods change the value(s) of instance variables.
•
The graphics module supplied with this book provides a number of classes that are useful for graphics programming. A
GraphWinis an object that represents a window on the screen for displaying graphics. Various graph
ical objects such as
Point, Line, Circle, Rectangle, Oval, Polygon,and
Text
may be drawn in a
GraphWin.Users may interact with a
GraphWinby clicking the mouse or typing into an
Entrybox.
• An
important consideration in graphical programming is the choice of an
appropriate coordinate system. The graphics library provides a way of
automating certain coordinate transformations.
4. 10. Exercises
•
The situation where two variables refer to the same object is called alias
ing. Aliasing can sometimes cause unexpected results. Use of the
clonemethod in the graphics library can help prevent these situations.
14.10 I Exercises
Review Questions
True/False
1. Using
graphics . pyallows graphics to be drawn in a Python shell window.
2. Traditionally, the upper-left comer of a graphics window has coordinates (0,0).
3. A single point on a graphics screen is called a pixel.
4. A function that creates a new instance of a class is called an accessor.
5. Instance variables are used to store data inside an object.
6. The statement
myShape . move ( 10 , 20)moves
myShapeto the point (1 0,20).
7. Aliasing occurs when two variables refer to the same object.
8. The
copymethod is provided to make a copy of a graphics object.
9. A graphics window always has the title "Graphics Window."
10. The method in the graphics library used to get a mouse click is
read.Mouse.Multiple Choice
1. A method that returns the value of an object's instance variable is called a(n)
a) mutator b) function c) constructor d) accessor
2. A method that changes the state of an object is called a(n) a) stator b) mutator c) constructor d) changor
3. What graphics class would be best for drawing a square?
a)
Squareb)
Polygonc)
Lined)
Rectangle123
4. What command would set the coordinates of
winto go from (0,0) in the lower-left corner to (10, 10) in the upper-right?
a) win . setcoords (Point (O , O) , Point ( 10 , 10) )
b)
win . setcoords ( (O , O) , ( 10 , 10) ) c) win . setcoords (O , 0 , 10 , 10)d) win . setcoords (Point ( 10 , 10) , Point (O , O) )
5. What expression would create a line from (2,3) to (4,5)?
a) Line (2 , 3 , 4 , 5)
b)
Line ( (2 , 3) , (4 , 5) )c)
Line (2 , 4 , 3 , 5)d) Line (Point (2 , 3) , Point (4 , 5) )
6. What command would be used to draw the graphics object
shapeinto the graphics window
win?a)
win . draw (shape)b)
win . show ( shape)c)
shape . draw ( )d)
shape . draw (win)7. Which of the following computes the horizontal distance between points
p1
and
p2?a)
abs (p1-p2)b)
p2 . get X ( ) - p 1 . get X ( )c)
abs (p1 . getY O - p2 . getY ( ) )d)
abs (p 1 . get X ( ) - p2 . get X ( ) )8. What kind of object can be used to get text input in a graphics window?
a)
Textb)
Entryc)
Inputd)
Keyboard9. A user interface organized around visual elements and user actions is called a(n)
a) GUI b) application c) windower d) API 10. What color is
color _rgb ( 0 , 255 , 255) ?a) yellow b) cyan c) magenta d) orange
Discussion
1. Pick an example of an interesting real-world object and describe it as a
programming object by listing its data (attributes, what it "knows") and
its methods (behaviors, what it can "do").
4. 10. Exercises
2. Describe in your own words the object produced by each of the following operations from the graphics module. Be as precise as you can. Be sure to mention such things as the size, position, and appearance of the various objects. You may include a sketch if that helps.
a)
Point ( 130 , 130)b)
c = Circle (Point (30 , 40) , 25) c . setFill ( "blue " )c . setOutline ( " red" )
c)
r = Rectangle (Point (20 , 20) , Point (40 , 40) ) r . setFill (color_rgb (0 , 255 , 150) )r . setWidth (3)
d)
1 = Line (Point ( 100 , 100) , Point ( 100 , 200) ) l . set0utline ( " red4" )l . setArrow ( '' f irst '' )
e)
Oval (Point (50 , 50) , Point (60 , 100) )125
f )
shape = Polygon (Point (5 , 5) , Point ( 10 , 10) , Point (5 , 10) , Point ( 10 , 5) ) shape . setFill ( " orange " )g)
t = Text (Point ( 100 , 100) , "Hello World ! " ) t . setFace ( " courier " )t . setSize ( 16)
t . setStyle ( '' italic'' )
3. Describe what happens when the following interactive graphics program runs:
from graphics import * def main ( ) :
win = GraphWin ( )
shape = Circle (Point (50 , 50) , 20) shape . setOutline ( " red" )
shape . setFill ( " red" ) shape . draw (win)
f or i in range ( 10) :
p = win . getMouse ( )
c = shape . getCenter ( ) dx = p . getX ( ) - c . getX ( )
dy = p . getY ( ) - c . getY ( ) shape . move (dx , dy)
win . close ( ) main ( )
Programming Exercises
1. Alter the program from the last discussion question in the following ways:
(a) Make it draw squares instead of circles.
(b) Have each successive click draw an additional square on the screen (rather than moving the existing one).
(c) Print a message on the window "Click again to quit" after the loop, and wait for a final click before closing the window.
2.
Anarchery target consists of a central circle of yellow surrounded by con
centric rings of red, blue, black and white. Each ring has the same width, which is the same as the radius of the yellow circle. Write a program that draws such a target. Hint: Objects drawn later will appear on top of objects drawn earlier.
3. Write a program that draws some sort of face.
4. Write a program that draws a winter scene with a Christmas tree and a snowman.
5. Write a program that draws 5 dice on the screen depicting a straight (1, 2, 3, 4, 5 or 2, 3, 4, 5, 6).
6. Modify the graphical future value program so that the input (principal and
APR) also are done in a graphical fashion using
Entryobjects.
4. 10. Exercises
7. Circle Intersection.
Write a program that computes the intersection of a circle with a hori
zontal line and displays the information textually and graphically.
Input: Radius of the circle and they-intercept of the line.
Output: Draw a circle centered at ( 0, 0 ) with the given radius in a window with coordinates running from -10,-10 to 10,10.
Draw a horizontal line across the window with the given y-intercept.
Draw the two points of intersection in red.
Print out the x values of the points of intersection.
Formula: x =
±y' r2 - y2
8. Line Segment Information.
This program allows the user to draw a line segment and then displays some graphical and textual information about the line segment.
Input: Two mouse clicks for the end points of the line segment.
Output: Draw the midpoint of the segment in cyan.
Draw the line.
Print the length and the slope of the line.
Formulas: dx = x2 - x1 dy = Y2 - Yl slope = dy / dx
length = J dx2 + d y 2 9. Rectangle Information.
This program displays information about a rectangle drawn by the user.
Input: Two mouse clicks for the opposite comers of a rectangle.
Output: Draw the rectangle.
Print the perimeter and area of the rectangle.
Formulas: area = (length)(width)
perimeter = 2(length + width)
127
10. Triangle Information.
Same as the previous problem, but with three clicks for the vertices of a triangle.
Formulas: For perimeter, see length from the Line Segment problem.
area = Js(s - a)(s - b)(s -
c) where a, b, and c are the lengths of the sides and s = a+�+c.
1 1. Five-click House.
You are to write a program that allows the user to draw a simple house using five mouse clicks. The first two clicks will be the opposite corners of the rectangular frame of the house. The third click will indicate the center of the top edge of a rectangular door. The door should have a total width that is � of the width of the house frame. The sides of the door should extend from the corners of the top down to the bottom of the frame. The fourth click will indicate the center of a square window. The window is half as wide as the door. The last click will indicate the peak of the roof.
The edges of the roof will extend from the point at the peak to the corners of the top edge of the house frame.
1
5
3