Overview
To use the graphics library, first import it at the top of your program:
from graphics import *
Here is a short example showing how to create a new graphics window object and then create gui objects to draw into this window:
win = GraphWin("Graphics!!!!!!", 500, 500) # create new GraphWin object, 500x500 pixels in size
win.setBackground("blue") # set the background color to blue
cp = Point(50,50) # creates a new Point object at 50,50
circ = Circle(cp, 20) # creates new Circle object centered at point cp with a radius of 20 pixels
circ.setFill("red") # invoke the setFill method of the Circle object referred to by circ
circ.draw(win) # draw the circ object to the GraphWin win
win.getMouse() # wait for user to click mouse
win.close() # close window
GraphWin
GraphWin(title, width, height)
Creates and returns a new GraphWin
object of given width
and height
in pixels. The provided title
string will appear at the top of the window.
getWidth()
Returns the width of the GraphWin
object in pixels
getHeight()
Returns the height of the GraphWin
object in pixels
setBackground(color)
Sets the fill color of the object to color
. The color
can be
specified as a Tcl/Tk
color string, a list of [r,g,b]
, or a color_rgb(r,g,b)
triple. See
the section on Colors for more details on specifying
colors.
getMouse()
Waits until the user clicks in the GraphWin
object and returns a new Point
object containing the coordinates of the mouse click location.
setCoords(xll, yll, xur, yur)
Sets the coordinate system of the current graphics window to have a lower left corner at (x,y) = (xll, yll)
and an upper right corner of (x,y) = (xur, yur)
. For example,
win = GraphWin("test", 500, 500)
win.setCoords(0,0,1,1)
#With these setCoords, the circle will appear in the middle
#of the screen and touch the sides of the window.
circ = Circle(Point(0.5,0.5), 0.5)
circ.draw(win)
close()
Closes the GraphWin
object. Attempting to draw to a closed GraphWin
object is an error.
getKey()
Waits until the user presses a key on the keyboard and returns a string representing the pressed key.
checkKey()
Similar to getKey
, but does not wait until a user presses a key. If the user is currently pressing a key, checkKey
immediately returns a string representing the pressed key. Otherwise, checkKey
returns an empty string ""
. This method is primarily used in interactive applications where checkKey
appears in a while
loop.
checkMouse()
Similar to getMouse
, but does not wait until a user clicks. If the user is currently holding the mouse button down, checkMouse
immediately returns a new Point
object containing the coordinates of the mouse click location. Otherwise, checkMouse
returns the special value None
. This method is primarily used in interactive applications where checkMouse
appears in a while
loop.
Common Methods
The geometry objects listed below (Point,Line,Rectangle,Circle,Oval,and Polygon) all support a set of common methods which are described once here.
draw(win)
Draws the corresponding graphics object in the GraphWin
object win
. Calling draw twice on the same object results in an error, unless the object is currently undrawn.
undraw()
Undraws or hide sthe object from its current GraphWin
object. It is legal to call undraw()
on an undrawn object. Nothing happens.
setFill(color)
Sets the fill color of the object to color
. The color
can be
specified as a Tcl/Tk
color string, a list of [r,g,b]
, or a color_rgb(r,g,b)
triple.
win = GraphWin("Test", 500, 500)
circ = Circle(Point(50,50), 20)
circ.setFill("lawn green")
circ.setOutline(color_rgb(200,0,200)) #purplish
win.getMouse() # pause before changing fill color
circ.setFill([250,128,0]) # good for halloween
circ.setWidth(10)
circ.draw(win)
See the section on Colors for more details on specifying colors.
setOutline(color)
Sets the outline color of the object to color
. Default color is black. In many applications, you may want to set the outline to be the same color as the fill color to avoid appearance of seams between adjacent shapes of the same color.
setWidth(width)
Changes the width of the outline of the object to width
pixels. Note that setWidth
causes an error when used on Point
objects, even though setOutline
does not.
move(dx,dy)
Moves the object dx
units in the \$x\$ direction: and dy
units in the \$y\$ direction. If the object is drawn, the move takes effect immediately.
clone()
Makes and returns a copy of the object with the same properties (geometry, color, width, etc.), but in an undrawn state. Use this to manipulate multiple copies of similar objects.
shape2
and shape
refer to the same object in problem known as aliasingshape2 = shape
shape2.setFill("blue")
shape2.move(10,10)
shape
that can manipulated independently. Don’t forget to draw the new shape.shape2 = shape.clone()
shape2.setFill("blue")
shape2.move(10,10)
shape2.draw(win)
Point
Point(x,y)
Constructs and returns a new point object at location (x,y)
.
getX()
Returns value of \$x\$ coordinate of point.
getY()
Returns value of \$y\$ coordinate of point.
See also the Common Methods for all geometry types.
Point()
Example
Assuming we already have a graphics window object win
:
p1 = Point(300, 450)
p1.draw(win)
x1 = p1.getX()
x2 = p1.getY()
print(x1,x2) # would just print 300 450
p2 = p1.clone() # make a copy of Point p1
p2.move(100,20) # move it
p2.draw(win)
Line
Line(p1, p2)
Constructs and returns a new Line object between two Point objects p1
and p2
.
getP1()
Returns a Point object representing the first endpoint of the line, p1
.
getP2()
Returns a Point object representing the second endpoint of the line, p2
.
getCenter()
Returns a Point object located on the line halfway between its enpoints p1
and `p2.
setArrow(option)
Adds an optional arrowhead to either end of the line. The option
value can be the string "first"
,"last"
, "both"
, or "none"
. Does not return anything.
See also the Common Methods for all geometry types.
Line()
Example
Assuming we already have a graphics window object win
:
p1 = Point(0, 250)
p2 = Point(600, 250)
horizontal_line = Line(p1, p2)
horizontal_line.setWidth(5)
horizontal_line.draw(win)
Rectangle
Rectangle(p1, p2)
Creates and return a new Rectangle object with opposite corners located at Point objects p1
and p2
.
getP1()
Returns a Point object representing the first corner of the rectangle, p1
.
getP2()
Returns a Point object representing the opposite corner of the rectangle, p2
.
getCenter()
Returns a Point object located in the middle of the rectangle halfway between a line connecting opposite corners p1
and p2
.
See also the Common Methods for all geometry types.
Rectangle()
Example
Assuming we already have a graphics window object win
:
p1 = Point(100, 100)
p2 = Point(200, 200)
square = Rectangle(p1, p2)
square.draw(win)
Circle
Circle(p1, radius)
Creates and returns a new Circle
object with radius radius
and center located at point p1
.
getRadius()
Returns the radius of the current circle.
getCenter()
Returns a Point object p1
located in the center of the circle.
getP1()
Returns a Point object representing the upper left corner of bounding box containing the circle.
getP2()
Returns a Point object representing the lower right corner of bounding box containing the circle.
See also the Common Methods for all geometry types.
Circle()
Example
Assuming we already have a graphics window object win
:
center = Point(100, 100)
radius = 35
sun = Circle(center, radius)
sun.setFill("yellow")
sun.setOutline("yellow")
sun.draw(win)
Oval
Oval(p1, p2)
Creates and returns a new Oval
object bounded by the bounding box defined by opposite corner points p1
and p2
.
getCenter()
getP1()
Returns a Point object representing the upper left corner of bounding box containing the oval.
getP2()
Returns a Point object representing the lower right corner of bounding box containing the oval.
See also the Common Methods for all geometry types.
Polygon
Polygon([p1, p2, p3, …])
Constructs and returns a new Polygon
object given a list of points defining the boundary vertices of the polygon. The brackets []
around the point list are optional.
#fine
tri = Polygon([Point(0,0), Point(50,0), Point(50,50)])
#also works
tri2 = Polygon(Point(0,0), Point(50,0), Point(50,50))
getPoints()
Returns a list containing all the Point objects defining the boundary of the polygon.
See also the Common Methods for all geometry types.
Text
Text(p,text_string)
Creates and returns a new Text
object with center located at
point p
. The text_string
variable holds the text to be
displayed.
getText()
Gets and returns the text of this Text Object as a string.
setText(text)
Changes the text of this Text object. If the Text object is currently drawn, the change is seen immediately.
getAnchor()
Returns clone of object anchor point.
setTextColor(color)
Sets the text color of this object.
setFace(family)
Sets the font face to the value of the string family
. Valid values of the family
variable are: "helvetica", "arial", "courier", and "times roman"
setSize(size)
Sets the font size of this object to size
. Values from 5-72 are legal.
setStyle(style)
Sets the font style to the string style
value. Valid options are: "bold", "normal", "italic", or "bold italic".
Text()
Example
Assuming we already have a graphics window object win
:
message = Text(Point(300, 100), "please click anywhere to close window")
message.setSize(24)
message.setTextColor("red")
message.draw(win)
See also the Common Methods for all geometry types.
Entry
We don’t use the Entry class much in CS21, but it provides a way to get text from the user from within the graphics window.
Entry(p,width)
Creates a rectangular text entry box centered at point p
that display width
characters typed by the user.
getText()
Gets and returns the text contained in this object as a string. A user can click inside the Entry
and change the text. getText
will return the modified text.
Common Text methods
Many methods of the Entry
class are similar to those of the Text
class. See the Text Documention for the methods getAnchor
, setTextColor
, setFace
, setSize
, and setStyle
.
See also the Common Methods for all geometry types.
Colors
For methods that request a color argument, you can specfify the color
as a Tcl/Tk color
string, you can use a list of [r,g,b]
, or you can use the
color_rgb(r, g, b)
function to create colors based on different
amount of red, green, and blue. Here’s an example of how it’s used:
p = Point(100,200)
c = Circle(p, 50)
mycolor = color_rgb(100,200,0)
c.setFill(mycolor)
c.setOutline([100, 149, 237]) # alternate format using a list
In the above example, the arguments to color_rgb()
are integers
representing the amount of red, green, and blue. They can be any
integer from 0-255. So the above color you get from color_rgb(100,
200, 0)
is a bright green (red=100, green=200, blue=0). Using
color_rgb(50, 50, 50)
would give a dark grey, and color_rgb(0, 255,
255)
would be cyan (red off, green and blue full on). Similarly, the
list [100, 149, 237]
yields the same color that color_rgb(100, 149,
237)
yields: cornflower blue.
red | green | blue | color |
---|---|---|---|
0 |
0 |
0 |
black |
255 |
255 |
255 |
white |
255 |
0 |
0 |
red |
0 |
255 |
0 |
green |
0 |
0 |
255 |
blue |
100 |
100 |
100 |
gray |
100 |
149 |
237 |
cornflower blue |
50 |
205 |
50 |
lime green |
Remember to use quotes if you are specifying a color string, e.g.,
"red"
, but not when you are using color_rgb
, e.g., clr =
color_rgb(255,0,0)
or a list, e.g. clr = [255, 0, 0]
On the CS network, we provide a small interactive color picker tool
$ python3
>>> from colorPicker import *
>>> colorPicker()
Clicking on a color will display both the string name and color_rgb
value in the terminal.
For a wider range of RGB colors, you can use a similar online color tool.
Other References
A PDF version of the graphic’s library documentation is available from Prof. John Zelle’s (the original author) website.