Contents

  1. animate2.py
  2. animate.py
  3. circleShift.py
  4. fenway.py
  5. game.py
  6. graphics.py
  7. graphics.pyc
  8. rectangle.py
  9. tictactoe2.py
  10. tictactoe.py
  11. userDraw.py

animate2.py 1/11

[
top][prev][next]
# This program is an example of how to create animation in a graphics
# window.  The user can indicate a new location for a circle.  The
# overall change in x and change in y is calculated.  Then the circle
# is moved in very small steps, with a slight pause in between, towards
# the final destination. 

from graphics import *
from time import sleep

FRAMES = 300


def main():
    w = GraphWin("Animate me!", 400, 400)
    w.setBackground("orange")

    current = Point(60,60)
    circ = Circle(current, 50)
    circ.setFill("yellow")
    circ.setWidth(3)
    circ.draw(w)

    message = Text(Point(200,380), "Click mouse on new location for circle")
    message.setSize(15)
    message.draw(w)

    for i in range(3):
        moveTo = w.getMouse()
        message.setText("Watch it move...")
        animate(circ, moveTo)
        message.setText("Click mouse on another new location")

    message.setText("Click once more to quit")
    w.getMouse()


# Input: move the shape object to the Point newPos
# Post-condition: the shape is centered at newPos
def animate( shape, newPos ):
    currPos = shape.getCenter()

    dx = float(newPos.getX() - currPos.getX())
    dy = float(newPos.getY() - currPos.getY())

    for step in range(FRAMES):
        shape.move(dx/FRAMES, dy/FRAMES)
        sleep(0.001)

main()

animate.py 2/11

[
top][prev][next]
# Simple demonstration of animation.
# by Sara Sprenkle, 10.29.2007

from graphics import *
from time import sleep

STEPS = 100

def main():
    w = GraphWin("Simple Animation", 400, 400)
    w.setBackground("orange")
    
    current = Point(60,60)
    circ = Circle(current, 50)
    circ.setFill("blue")
    circ.draw(w)

    end = w.getWidth()
    dx = (end - current.getX())/STEPS

    for step in range(STEPS):
        circ.move(dx, 0)
        sleep(.1)

    w.getMouse()

main()

circleShift.py 3/11

[
top][prev][next]
# This program draws an initial circle in the graphics window.
# Each time the user clicks on a new spot, the circle is
# shifted to that location.  This happens four times. On the fifth
# mouse click the program ends.

from graphics import *

def main():
    win = GraphWin("Moving Circles")
    circ = Circle(Point(50,50), 20)
    circ.setOutline("magenta")
    circ.setFill("magenta")
    circ.draw(win)

    label = Text(Point(100,180), "Click where the circle goes")
    label.draw(win)
    
    for i in range(5):
        moveTo = win.getMouse()
        current = circ.getCenter()
        dx = moveTo.getX() - current.getX()
        dy = moveTo.getY() - current.getY()
        circ.move(dx,dy)
        label.setText( str(5-i-1) + " clicks left")


main()
                   

fenway.py 4/11

[
top][prev][next]
"""
 How hard do you have to hit a baseball to hit it over 
 the Green Monster at Fenway Park? Run this program to test 
 your guesses.

 Author: Andrew Danner, 09.20.2007
"""

from graphics import *
from time import sleep
from math import *

MPH2FPS = 5280.0/3600. #conversion from mph to fps
DEG2RAD = pi/180.0 #conversion from degrees to radians
GRAVITY=32  #gravity in ft/s^2
NUM_STEPS = 70

def main():

  mph = input("Enter the speed off the bat in mph: ")
  angle = input("Enter a angle in degrees: ")

  win=GraphWin("Fenway", 700, 600)
  win.setBackground("lightblue")
  win.setCoords(0, 0, 350, 300)

  greenMonster = Rectangle(Point(304,0), Point(310, 37))
  greenMonster.setFill("darkgreen")
  greenMonster.setOutline("darkgreen")
  greenMonster.draw(win)

  fallTime = timeToFall(angle, mph)
  vx = changeInXVelocity(angle, mph)
  vy = changeInYVelocity(angle, mph)

  for t in xrange(NUM_STEPS):
    tnow = t/fallTime
    #assume initial ball height of 4 feet
    y = 4+vy*tnow - 0.5*GRAVITY*tnow*tnow
    x = vx*tnow
    ball = Circle(Point(x,y),3)
    ball.setFill("white")
    ball.draw(win)
    sleep(fallTime/NUM_STEPS)
  
  win.getMouse()
  win.close()


# Compute the time for the ball to fall, plus a few seconds.
# Input: the angle (in degrees) and the speed the ball was hit at (in
# miles per hour)
# Returns the time in seconds for the ball to fall
def timeToFall(angle, mph):
  theta = angle * DEG2RAD
  v = mph * MPH2FPS
  vy = v*sin(theta)
  vx = v*cos(theta)
  tf = 2*vy/GRAVITY  #time it takes to fall back down, plus a few secs
  return tf

# Compute the change in vertical velocity
def changeInYVelocity(angle, mph):
  theta = angle * DEG2RAD
  v = mph * MPH2FPS
  return v*sin(theta)

# Compute the change in horizontal velocity
def changeInXVelocity(angle, mph):
  theta = angle * DEG2RAD
  v = mph * MPH2FPS
  return v*cos(theta)



main()

game.py 5/11

[
top][prev][next]
# Game Module
# Contains useful functions and modules for various games
# by Sara Sprenkle, 10.24.2007


import random

# constants for flipping a coin
HEADS = 0
TAILS = 1

def testMe():
    rollDie(6)
    rollDie()
    rollDie(12)

# No pre- or post- condition
# return HEADS or TAILS, randomly
def coinFlip():
    return random.randint(0,1)

# input: the number of sides of the die (defaults to 6)
# return a random number between 1 and sides, inclusive
def rollDie(sides=6):
    print "Num sides =", sides
    return random.randint(1,sides)


# Remove this line after done testing.
# Otherwise, will call the testMe function when game module is
# imported.
testMe()

graphics.py 6/11

[
top][prev][next]
# graphics.py
"""Simple object oriented graphics library

The library is designed to make it very easy for novice programmers to
experiment with computer graphics in an object oriented fashion. It is
written by John Zelle for use with the book "Python Programming: An
Introduction to Computer Science" (Franklin, Beedle & Associates).

LICENSE: This is open-source software released under the terms of the
GPL (http://www.gnu.org/licenses/gpl.html).

PLATFORMS: The package is a wrapper around Tkinter and should run on
any platform where Tkinter is available.

INSTALLATION: Put this file somewhere where Python can see it.

OVERVIEW: There are two kinds of objects in the library. The GraphWin
class implements a window where drawing can be done and various
GraphicsObjects are provided that can be drawn into a GraphWin. As a
simple example, here is a complete program to draw a circle of radius
10 centered in a 100x100 window:

--------------------------------------------------------------------
from graphics import *

def main():
    win = GraphWin("My Circle", 100, 100)
    c = Circle(Point(50,50), 10)
    c.draw(win)
    win.getMouse() // Pause to view result

main()
--------------------------------------------------------------------
GraphWin objects support coordinate transformation through the
setCoords method and pointer-based input through getMouse.

The library provides the following graphical objects:
    Point
    Line
    Circle
    Oval
    Rectangle
    Polygon
    Text
    Entry (for text-based input)
    Image

Various attributes of graphical objects can be set such as
outline-color, fill-color and line-width. Graphical objects also
support moving and hiding for animation effects.

The library also provides a very simple class for pixel-based image
manipulation, Pixmap. A pixmap can be loaded from a file and displayed
using an Image object. Both getPixel and setPixel methods are provided
for manipulating the image.

DOCUMENTATION: For complete documentation, see Chapter 5 of "Python
Programming: An Introduction to Computer Science" by John Zelle,
published by Franklin, Beedle & Associates.  Also see
http://mcsp.wartburg.edu/zelle/python for a quick reference"""

# Version 3.3 8/8/06
#     Added checkMouse method to GraphWin
# Version 3.2.2 5/30/05
#     Cleaned up handling of exceptions in Tk thread. The graphics package
#     now raises an exception if attempt is made to communicate with
#     a dead Tk thread.
# Version 3.2.1 5/22/05
#     Added shutdown function for tk thread to eliminate race-condition
#        error "chatter" when main thread terminates
#     Renamed various private globals with _
# Version 3.2 5/4/05
#     Added Pixmap object for simple image manipulation.
# Version 3.1 4/13/05
#     Improved the Tk thread communication so that most Tk calls
#        do not have to wait for synchonization with the Tk thread.
#        (see _tkCall and _tkExec)
# Version 3.0 12/30/04
#     Implemented Tk event loop in separate thread. Should now work
#        interactively with IDLE. Undocumented autoflush feature is
#        no longer necessary. Its default is now False (off). It may
#        be removed in a future version.
#     Better handling of errors regarding operations on windows that
#       have been closed.
#     Addition of an isClosed method to GraphWindow class.

# Version 2.2 8/26/04
#     Fixed cloning bug reported by Joseph Oldham.
#     Now implements deep copy of config info.
# Version 2.1 1/15/04
#     Added autoflush option to GraphWin. When True (default) updates on
#        the window are done after each action. This makes some graphics
#        intensive programs sluggish. Turning off autoflush causes updates
#        to happen during idle periods or when flush is called.
# Version 2.0
#     Updated Documentation
#     Made Polygon accept a list of Points in constructor
#     Made all drawing functions call TK update for easier animations
#          and to make the overall package work better with
#          Python 2.3 and IDLE 1.0 under Windows (still some issues).
#     Removed vestigial turtle graphics.
#     Added ability to configure font for Entry objects (analogous to Text)
#     Added setTextColor for Text as an alias of setFill
#     Changed to class-style exceptions
#     Fixed cloning of Text objects

# Version 1.6
#     Fixed Entry so StringVar uses _root as master, solves weird
#            interaction with shell in Idle
#     Fixed bug in setCoords. X and Y coordinates can increase in
#           "non-intuitive" direction.
#     Tweaked wm_protocol so window is not resizable and kill box closes.

# Version 1.5
#     Fixed bug in Entry. Can now define entry before creating a
#     GraphWin. All GraphWins are now toplevel windows and share
#     a fixed root (called _root).

# Version 1.4
#     Fixed Garbage collection of Tkinter images bug.
#     Added ability to set text atttributes.
#     Added Entry boxes.

import time, os, sys
import Tkinter
tk = Tkinter


##########################################################################
# Module Exceptions

import exceptions

class GraphicsError(exceptions.Exception):
    """Generic error class for graphics module exceptions."""
    def __init__(self, args=None):
        self.args=args

OBJ_ALREADY_DRAWN = "Object currently drawn"
UNSUPPORTED_METHOD = "Object doesn't support operation"
BAD_OPTION = "Illegal option value"
DEAD_THREAD = "Graphics thread quit unexpectedly"

###########################################################################
# Support to run Tk in a separate thread

from copy import copy
from Queue import Queue
import thread
import atexit


_tk_request = Queue(0)
_tk_result = Queue(1)
_POLL_INTERVAL = 10

_root = None
_thread_running = True
_exception_info = None

def _tk_thread():
    global _root
    _root = tk.Tk()
    _root.withdraw()
    _root.after(_POLL_INTERVAL, _tk_pump)
    _root.mainloop()

def _tk_pump():
    global _thread_running
    while not _tk_request.empty():
        command,returns_value = _tk_request.get()
        try:
            result = command()
            if returns_value:
                _tk_result.put(result)
        except:
            _thread_running = False
            if returns_value:
                _tk_result.put(None) # release client
            raise # re-raise the exception -- kills the thread
    if _thread_running:
        _root.after(_POLL_INTERVAL, _tk_pump)

def _tkCall(f, *args, **kw):
    # execute synchronous call to f in the Tk thread
    # this function should be used when a return value from
    #   f is required or when synchronizing the threads.
    # call to _tkCall in Tk thread == DEADLOCK !
    if not _thread_running:
        raise GraphicsError, DEAD_THREAD
    def func():
        return f(*args, **kw)
    _tk_request.put((func,True),True)
    result = _tk_result.get(True)
    return result

def _tkExec(f, *args, **kw):
    # schedule f to execute in the Tk thread. This function does
    #   not wait for f to actually be executed.
    #global _exception_info
    #_exception_info = None
    if not _thread_running:
        raise GraphicsError, DEAD_THREAD
    def func():
        return f(*args, **kw)
    _tk_request.put((func,False),True)
    #if _exception_info is not None:
    #    raise GraphicsError, "Invalid Operation: %s" % str(_exception_info)

def _tkShutdown():
    # shutdown the tk thread
    global _thread_running
    #_tkExec(sys.exit)
    _thread_running = False
    time.sleep(.5) # give tk thread time to quit

# Fire up the separate Tk thread
thread.start_new_thread(_tk_thread,())

# Kill the tk thread at exit
atexit.register(_tkShutdown)

############################################################################
# Graphics classes start here
        
class GraphWin(tk.Canvas):

    """A GraphWin is a toplevel window for displaying graphics."""

    def __init__(self, title="Graphics Window",
                 width=200, height=200, autoflush=False):
        _tkCall(self.__init_help, title, width, height, autoflush)
 
    
    def __init_help(self, title, width, height, autoflush):
        master = tk.Toplevel(_root)
        master.protocol("WM_DELETE_WINDOW", self.__close_help)
        tk.Canvas.__init__(self, master, width=width, height=height)
        self.master.title(title)
        self.pack()
        master.resizable(0,0)
        self.foreground = "black"
        self.items = []
        self.mouseX = None
        self.mouseY = None
        self.bind("<Button-1>", self._onClick)
        self.height = height
        self.width = width
        self.autoflush = autoflush
        self._mouseCallback = None
        self.trans = None
        self.closed = False
        if autoflush: _root.update()

    def __checkOpen(self):
        if self.closed:
            raise GraphicsError, "window is closed"

    def setBackground(self, color):
        """Set background color of the window"""
        self.__checkOpen()
        _tkExec(self.config, bg=color)
        #self.config(bg=color)
        
    def setCoords(self, x1, y1, x2, y2):
        """Set coordinates of window to run from (x1,y1) in the
        lower-left corner to (x2,y2) in the upper-right corner."""
        self.trans = Transform(self.width, self.height, x1, y1, x2, y2)

    def close(self):
        if self.closed: return
        _tkCall(self.__close_help)
        
    def __close_help(self):
        """Close the window"""
        self.closed = True
        self.master.destroy()
        _root.update()

    def isClosed(self):
        return self.closed

    def __autoflush(self):
        if self.autoflush:
            _tkCall(_root.update)
    
    def plot(self, x, y, color="black"):
        """Set pixel (x,y) to the given color"""
        self.__checkOpen()
        xs,ys = self.toScreen(x,y)
        #self.create_line(xs,ys,xs+1,ys, fill=color)
        _tkExec(self.create_line,xs,ys,xs+1,ys,fill=color)
        self.__autoflush()
        
    def plotPixel(self, x, y, color="black"):
        """Set pixel raw (independent of window coordinates) pixel
        (x,y) to color"""
        self.__checkOpen()
    	#self.create_line(x,y,x+1,y, fill=color)
        _tkExec(self.create_line, x,y,x+1,y, fill=color)
        self.__autoflush()
    	
    def flush(self):
        """Update drawing to the window"""
        #self.update_idletasks()
        self.__checkOpen()
        _tkCall(self.update_idletasks)
        
    def getMouse(self):
        """Wait for mouse click and return Point object representing
        the click"""
        self.mouseX = None
        self.mouseY = None
        while self.mouseX == None or self.mouseY == None:
            #self.update()
            _tkCall(self.update)
            if self.isClosed(): raise GraphicsError, "getMouse in closed window"
            time.sleep(.1) # give up thread
        x,y = self.toWorld(self.mouseX, self.mouseY)
        self.mouseX = None
        self.mouseY = None
        return Point(x,y)

    def checkMouse(self):
        """Return mouse click last mouse click or None if mouse has
        not been clicked since last call"""
        if self.isClosed():
            raise GraphicsError, "checkMouse in closed window"
        _tkCall(self.update)
        if self.mouseX != None and self.mouseY != None:
            x,y = self.toWorld(self.mouseX, self.mouseY)
            self.mouseX = None
            self.mouseY = None
            return Point(x,y)
        else:
            return None
            
    def getHeight(self):
        """Return the height of the window"""
        return self.height
        
    def getWidth(self):
        """Return the width of the window"""
        return self.width
    
    def toScreen(self, x, y):
        trans = self.trans
        if trans:
            return self.trans.screen(x,y)
        else:
            return x,y
                      
    def toWorld(self, x, y):
        trans = self.trans
        if trans:
            return self.trans.world(x,y)
        else:
            return x,y
        
    def setMouseHandler(self, func):
        self._mouseCallback = func
        
    def _onClick(self, e):
        self.mouseX = e.x
        self.mouseY = e.y
        if self._mouseCallback:
            self._mouseCallback(Point(e.x, e.y)) 
                      
class Transform:

    """Internal class for 2-D coordinate transformations"""
    
    def __init__(self, w, h, xlow, ylow, xhigh, yhigh):
        # w, h are width and height of window
        # (xlow,ylow) coordinates of lower-left [raw (0,h-1)]
        # (xhigh,yhigh) coordinates of upper-right [raw (w-1,0)]
        xspan = (xhigh-xlow)
        yspan = (yhigh-ylow)
        self.xbase = xlow
        self.ybase = yhigh
        self.xscale = xspan/float(w-1)
        self.yscale = yspan/float(h-1)
        
    def screen(self,x,y):
        # Returns x,y in screen (actually window) coordinates
        xs = (x-self.xbase) / self.xscale
        ys = (self.ybase-y) / self.yscale
        return int(xs+0.5),int(ys+0.5)
        
    def world(self,xs,ys):
        # Returns xs,ys in world coordinates
        x = xs*self.xscale + self.xbase
        y = self.ybase - ys*self.yscale
        return x,y


# Default values for various item configuration options. Only a subset of
#   keys may be present in the configuration dictionary for a given item
DEFAULT_CONFIG = {"fill":"",
		  "outline":"black",
		  "width":"1",
		  "arrow":"none",
		  "text":"",
		  "justify":"center",
                  "font": ("helvetica", 12, "normal")}

class GraphicsObject:

    """Generic base class for all of the drawable objects"""
    # A subclass of GraphicsObject should override _draw and
    #   and _move methods.
    
    def __init__(self, options):
        # options is a list of strings indicating which options are
        # legal for this object.
        
        # When an object is drawn, canvas is set to the GraphWin(canvas)
        #    object where it is drawn and id is the TK identifier of the
        #    drawn shape.
        self.canvas = None
        self.id = None

        # config is the dictionary of configuration options for the widget.
        config = {}
        for option in options:
            config[option] = DEFAULT_CONFIG[option]
        self.config = config
        
    def setFill(self, color):
        """Set interior color to color"""
        self._reconfig("fill", color)
        
    def setOutline(self, color):
        """Set outline color to color"""
        self._reconfig("outline", color)
        
    def setWidth(self, width):
        """Set line weight to width"""
        self._reconfig("width", width)

    def draw(self, graphwin):

        """Draw the object in graphwin, which should be a GraphWin
        object.  A GraphicsObject may only be drawn into one
        window. Raises an error if attempt made to draw an object that
        is already visible."""

        if self.canvas and not self.canvas.isClosed(): raise GraphicsError, OBJ_ALREADY_DRAWN
        if graphwin.isClosed(): raise GraphicsError, "Can't draw to closed window"
        self.canvas = graphwin
        #self.id = self._draw(graphwin, self.config)
        self.id = _tkCall(self._draw, graphwin, self.config)
        if graphwin.autoflush:
            #_root.update()
            _tkCall(_root.update)

    def undraw(self):

        """Undraw the object (i.e. hide it). Returns silently if the
        object is not currently drawn."""
        
        if not self.canvas: return
        if not self.canvas.isClosed():
            #self.canvas.delete(self.id)
            _tkExec(self.canvas.delete, self.id)
            if self.canvas.autoflush:
                #_root.update()
                _tkCall(_root.update)
        self.canvas = None
        self.id = None

    def move(self, dx, dy):

        """move object dx units in x direction and dy units in y
        direction"""
        
        self._move(dx,dy)
        canvas = self.canvas
        if canvas and not canvas.isClosed():
            trans = canvas.trans
            if trans:
                x = dx/ trans.xscale 
                y = -dy / trans.yscale
            else:
                x = dx
                y = dy
            #self.canvas.move(self.id, x, y)
            _tkExec(self.canvas.move, self.id, x, y)
            if canvas.autoflush:
                #_root.update()
                _tkCall(_root.update)
           
    def _reconfig(self, option, setting):
        # Internal method for changing configuration of the object
        # Raises an error if the option does not exist in the config
        #    dictionary for this object
        if not self.config.has_key(option):
            raise GraphicsError, UNSUPPORTED_METHOD
        options = self.config
        options[option] = setting
        if self.canvas and not self.canvas.isClosed():
            #self.canvas.itemconfig(self.id, options)
            _tkExec(self.canvas.itemconfig, self.id, options)
            if self.canvas.autoflush:
                #_root.update()
                _tkCall(_root.update)

    def _draw(self, canvas, options):
        """draws appropriate figure on canvas with options provided
        Returns Tk id of item drawn"""
        pass # must override in subclass

    def _move(self, dx, dy):
        """updates internal state of object to move it dx,dy units"""
        pass # must override in subclass
         
class Point(GraphicsObject):
    def __init__(self, x, y):
        GraphicsObject.__init__(self, ["outline", "fill"])
        self.setFill = self.setOutline
        self.x = x
        self.y = y
        
    def _draw(self, canvas, options):
        x,y = canvas.toScreen(self.x,self.y)
        return canvas.create_rectangle(x,y,x+1,y+1,options)
        
    def _move(self, dx, dy):
        self.x = self.x + dx
        self.y = self.y + dy
        
    def clone(self):
        other = Point(self.x,self.y)
        other.config = self.config.copy()
        return other
                
    def getX(self): return self.x
    def getY(self): return self.y

class _BBox(GraphicsObject):
    # Internal base class for objects represented by bounding box
    # (opposite corners) Line segment is a degenerate case.
    
    def __init__(self, p1, p2, options=["outline","width","fill"]):
        GraphicsObject.__init__(self, options)
        self.p1 = p1.clone()
	self.p2 = p2.clone()

    def _move(self, dx, dy):
        self.p1.x = self.p1.x + dx
        self.p1.y = self.p1.y + dy
        self.p2.x = self.p2.x + dx
        self.p2.y = self.p2.y  + dy
                
    def getP1(self): return self.p1.clone()

    def getP2(self): return self.p2.clone()
    
    def getCenter(self):
        p1 = self.p1
        p2 = self.p2
        return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)
    
class Rectangle(_BBox):
    
    def __init__(self, p1, p2):
        _BBox.__init__(self, p1, p2)
    
    def _draw(self, canvas, options):
        p1 = self.p1
        p2 = self.p2
        x1,y1 = canvas.toScreen(p1.x,p1.y)
        x2,y2 = canvas.toScreen(p2.x,p2.y)
        return canvas.create_rectangle(x1,y1,x2,y2,options)
        
    def clone(self):
        other = Rectangle(self.p1, self.p2)
        other.config = self.config.copy()
        return other
        
class Oval(_BBox):
    
    def __init__(self, p1, p2):
        _BBox.__init__(self, p1, p2)
        
    def clone(self):
        other = Oval(self.p1, self.p2)
        other.config = self.config.copy()
        return other
   
    def _draw(self, canvas, options):
        p1 = self.p1
        p2 = self.p2
        x1,y1 = canvas.toScreen(p1.x,p1.y)
        x2,y2 = canvas.toScreen(p2.x,p2.y)
        return canvas.create_oval(x1,y1,x2,y2,options)
    
class Circle(Oval):
    
    def __init__(self, center, radius):
        p1 = Point(center.x-radius, center.y-radius)
        p2 = Point(center.x+radius, center.y+radius)
        Oval.__init__(self, p1, p2)
        self.radius = radius
        
    def clone(self):
        other = Circle(self.getCenter(), self.radius)
        other.config = self.config.copy()
        return other
        
    def getRadius(self):
        return self.radius
              
class Line(_BBox):
    
    def __init__(self, p1, p2):
        _BBox.__init__(self, p1, p2, ["arrow","fill","width"])
        self.setFill(DEFAULT_CONFIG['outline'])
        self.setOutline = self.setFill
   
    def clone(self):
        other = Line(self.p1, self.p2)
        other.config = self.config.copy()
        return other
	
    def _draw(self, canvas, options):
        p1 = self.p1
        p2 = self.p2
        x1,y1 = canvas.toScreen(p1.x,p1.y)
        x2,y2 = canvas.toScreen(p2.x,p2.y)
        return canvas.create_line(x1,y1,x2,y2,options)
        
    def setArrow(self, option):
        if not option in ["first","last","both","none"]:
            raise GraphicsError, BAD_OPTION
        self._reconfig("arrow", option)
        

class Polyline(GraphicsObject):
    
    def __init__(self, *points):
        # if points passed as a list, extract it
        if len(points) == 1 and type(points[0] == type([])):
            points = points[0]
        self.points = map(Point.clone, points)

        #to simulate a polyline, we're drawing a polyline by
        #drawing a degenerate polygon back on itself
        self.revpoints = [x for x in self.points]
        self.revpoints.reverse()
        self.points.extend(self.revpoints)
        
        GraphicsObject.__init__(self, ["outline", "width", "fill"])
        
    def clone(self):
        other = apply(Polyline, self.points)
        other.config = self.config.copy()
        return other

    def getPoints(self):
        #when a user asks for the points, don't give them the
        #degenerate points.
        return map(Point.clone, self.points[0:len(self.points)/2])

    def _move(self, dx, dy):
        for p in self.points:
            p.move(dx,dy)
   
    def _draw(self, canvas, options):
        args = [canvas]
        for p in self.points:
            x,y = canvas.toScreen(p.x,p.y)
            args.append(x)
            args.append(y)
        args.append(options)
        return apply(GraphWin.create_polygon, args) 

class Polygon(GraphicsObject):
    
    def __init__(self, *points):
        # if points passed as a list, extract it
        if len(points) == 1 and type(points[0] == type([])):
            points = points[0]
        self.points = map(Point.clone, points)
        GraphicsObject.__init__(self, ["outline", "width", "fill"])
        
    def clone(self):
        other = apply(Polygon, self.points)
        other.config = self.config.copy()
        return other

    def getPoints(self):
        return map(Point.clone, self.points)

    def _move(self, dx, dy):
        for p in self.points:
            p.move(dx,dy)
   
    def _draw(self, canvas, options):
        args = [canvas]
        for p in self.points:
            x,y = canvas.toScreen(p.x,p.y)
            args.append(x)
            args.append(y)
        args.append(options)
        return apply(GraphWin.create_polygon, args) 

class Text(GraphicsObject):
    
    	def __init__(self, p, text):
    		GraphicsObject.__init__(self, ["justify","fill","text","font"])
    		self.setText(text)
    		self.anchor = p.clone()
    		self.setFill(DEFAULT_CONFIG['outline'])
                self.setOutline = self.setFill
    		
    	def _draw(self, canvas, options):
    		p = self.anchor
    		x,y = canvas.toScreen(p.x,p.y)
    		return canvas.create_text(x,y,options)
    		
    	def _move(self, dx, dy):
    		self.anchor.move(dx,dy)
    		
    	def clone(self):
    		other = Text(self.anchor, self.config['text'])
    		other.config = self.config.copy()
    		return other

    	def setText(self,text):
    		self._reconfig("text", text)
    		
    	def getText(self):
    		return self.config["text"]
    	    	
    	def getAnchor(self):
    		return self.anchor.clone()

        def setFace(self, face):
            if face in ['helvetica','arial','courier','times roman']:
                f,s,b = self.config['font']
                self._reconfig("font",(face,s,b))
            else:
                raise GraphicsError, BAD_OPTION

        def setSize(self, size):
            if 5 <= size <= 36:
                f,s,b = self.config['font']
                self._reconfig("font", (f,size,b))
            else:
                raise GraphicsError, BAD_OPTION

        def setStyle(self, style):
            if style in ['bold','normal','italic', 'bold italic']:
                f,s,b = self.config['font']
                self._reconfig("font", (f,s,style))
            else:
                raise GraphicsError, BAD_OPTION

        def setTextColor(self, color):
            self.setFill(color)


class Entry(GraphicsObject):

    def __init__(self, p, width):
        GraphicsObject.__init__(self, [])
        self.anchor = p.clone()
        #print self.anchor
        self.width = width
        #self.text = tk.StringVar(_root)
        #self.text.set("")
        self.text = _tkCall(tk.StringVar, _root)
        _tkCall(self.text.set, "")
        self.fill = "gray"
        self.color = "black"
        self.font = DEFAULT_CONFIG['font']
        self.entry = None

    def _draw(self, canvas, options):
        p = self.anchor
        x,y = canvas.toScreen(p.x,p.y)
        frm = tk.Frame(canvas.master)
        self.entry = tk.Entry(frm,
                              width=self.width,
                              textvariable=self.text,
                              bg = self.fill,
                              fg = self.color,
                              font=self.font)
        self.entry.pack()
        #self.setFill(self.fill)
        return canvas.create_window(x,y,window=frm)

    def getText(self):
        return _tkCall(self.text.get)

    def _move(self, dx, dy):
        self.anchor.move(dx,dy)

    def getAnchor(self):
        return self.anchor.clone()

    def clone(self):
        other = Entry(self.anchor, self.width)
        return _tkCall(self.__clone_help, other)

    def __clone_help(self, other):
        other.config = self.config.copy()
        other.text = tk.StringVar()
        other.text.set(self.text.get())
        other.fill = self.fill
        return other

    def setText(self, t):
        #self.text.set(t)
        _tkCall(self.text.set, t)
            
    def setFill(self, color):
        self.fill = color
        if self.entry:
            #self.entry.config(bg=color)
            _tkExec(self.entry.config,bg=color)

    def _setFontComponent(self, which, value):
        font = list(self.font)
        font[which] = value
        self.font = tuple(font)
        if self.entry:
            #self.entry.config(font=self.font)
            _tkExec(self.entry.config, font=self.font)

    def setFace(self, face):
        if face in ['helvetica','arial','courier','times roman']:
            self._setFontComponent(0, face)
        else:
            raise GraphicsError, BAD_OPTION

    def setSize(self, size):
        if 5 <= size <= 36:
            self._setFontComponent(1,size)
        else:
            raise GraphicsError, BAD_OPTION

    def setStyle(self, style):
        if style in ['bold','normal','italic', 'bold italic']:
            self._setFontComponent(2,style)
        else:
            raise GraphicsError, BAD_OPTION

    def setTextColor(self, color):
        self.color=color
        if self.entry:
            #self.entry.config(fg=color)
            _tkExec(self.entry.config,fg=color)


class Image(GraphicsObject):

    idCount = 0
    imageCache = {} # tk photoimages go here to avoid GC while drawn 
    
    def __init__(self, p, pixmap):
        GraphicsObject.__init__(self, [])
        self.anchor = p.clone()
        self.imageId = Image.idCount
        Image.idCount = Image.idCount + 1
        if type(pixmap) == type(""):
            self.img = tk.PhotoImage(file=pixmap, master=_root)
        else:
            self.img = pixmap.image
            		
    def _draw(self, canvas, options):
        p = self.anchor
        x,y = canvas.toScreen(p.x,p.y)
        self.imageCache[self.imageId] = self.img # save a reference  
        return canvas.create_image(x,y,image=self.img)
    
    def _move(self, dx, dy):
        self.anchor.move(dx,dy)
        
    def undraw(self):
        del self.imageCache[self.imageId]  # allow gc of tk photoimage
        GraphicsObject.undraw(self)

    def getAnchor(self):
        return self.anchor.clone()
    		
    def clone(self):
        imgCopy = Pixmap(_tkCall(self.img.copy))
        other = Image(self.anchor, imgCopy)
        other.config = self.config.copy()
        return other


class Pixmap:
    """Pixmap represents an image as a 2D array of color values.
    A Pixmap can be made from a file (gif or ppm):

       pic = Pixmap("myPicture.gif")
       
    or initialized to a given size (initially transparent):

       pic = Pixmap(512, 512)


    """

    def __init__(self, *args):
        if len(args) == 1: # a file name or pixmap
            if type(args[0]) == type(""):
                self.image = _tkCall(tk.PhotoImage, file=args[0], master=_root)
            else:
                self.image = args[0]
        else: # arguments are width and height
            width, height = args
            self.image = _tkCall(tk.PhotoImage, master=_root,
                                width=width, height=height)
    
    def getWidth(self):
        """Returns the width of the image in pixels"""
        return _tkCall(self.image.width)

    def getHeight(self):
        """Returns the height of the image in pixels"""
        return _tkCall(self.image.height)

    def getPixel(self, x, y):
        """Returns a list [r,g,b] with the RGB color values for pixel (x,y)
        r,g,b are in range(256)

        """
        
        value = _tkCall(self.image.get, x,y)
        if type(value) ==  int:
            return [value, value, value]
        else:
            return map(int, value.split())



    def setPixel(self, x, y, (r,g,b)):
        """Sets pixel (x,y) to the color given by RGB values r, g, and b.
        r,g,b should be in range(256)

        """
        
        _tkExec(self.image.put, "{%s}"%color_rgb(r,g,b), (x, y))

    

    def clone(self):
        """Returns a copy of this Pixmap"""
        return Pixmap(self.image.copy())

    def save(self, filename):
        """Saves the pixmap image to filename.
        The format for the save image is determined from the filname extension.

        """
        
        path, name = os.path.split(filename)
        ext = name.split(".")[-1]
        _tkExec(self.image.write, filename, format=ext)

        
def color_rgb(r,g,b):
    """r,g,b are intensities of red, green, and blue in range(256)
    Returns color specifier string for the resulting color"""
    return "#%02x%02x%02x" % (r,g,b)

def test():
    win = GraphWin()
    win.setCoords(0,0,10,10)
    t = Text(Point(5,5), "Centered Text")
    t.draw(win)
    p = Polygon(Point(1,1), Point(5,3), Point(2,7))
    p.draw(win)
    e = Entry(Point(5,6), 10)
    e.draw(win)
    win.getMouse()
    p.setFill("red")
    p.setOutline("blue")
    p.setWidth(2)
    s = ""
    for pt in p.getPoints():
        s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
    t.setText(e.getText())
    e.setFill("green")
    e.setText("Spam!")
    e.move(2,0)
    win.getMouse()
    p.move(2,3)
    s = ""
    for pt in p.getPoints():
        s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
    t.setText(s)
    win.getMouse()
    p.undraw()
    e.undraw()
    t.setStyle("bold")
    win.getMouse()
    t.setStyle("normal")
    win.getMouse()
    t.setStyle("italic")
    win.getMouse()
    t.setStyle("bold italic")
    win.getMouse()
    t.setSize(14)
    win.getMouse()
    t.setFace("arial")
    t.setSize(20)
    win.getMouse()
    win.close()

if __name__ == "__main__":
    test()

graphics.pyc 7/11

[
top][prev][next]

L&Gc@sdZddkZddkZddkZddkZeZddkZdeifdYZdZ	dZ
dZdZdd	k
l
Z
dd
klZddkZddkZedZedZd
ZdaeadZdZdZdZdZdZeiedCeiedei fdYZ!ddDdYZ"hdd<dd<dd<dd<dd<d d!<dEd%<Z#d&dFd'YZ$d(e$fd)YZ%d*e$fd+YZ&d,e&fd-YZ'd.e&fd/YZ(d0e(fd1YZ)d2e&fd3YZ*d4e$fd5YZ+d6e$fd7YZ,d8e$fd9YZ-d:e$fd;YZ.d<e$fd=YZ/d>dGd?YZ0d@Z1dAZ2e3dBjoe2ndS(HsSimple object oriented graphics library

The library is designed to make it very easy for novice programmers to
experiment with computer graphics in an object oriented fashion. It is
written by John Zelle for use with the book "Python Programming: An
Introduction to Computer Science" (Franklin, Beedle & Associates).

LICENSE: This is open-source software released under the terms of the
GPL (http://www.gnu.org/licenses/gpl.html).

PLATFORMS: The package is a wrapper around Tkinter and should run on
any platform where Tkinter is available.

INSTALLATION: Put this file somewhere where Python can see it.

OVERVIEW: There are two kinds of objects in the library. The GraphWin
class implements a window where drawing can be done and various
GraphicsObjects are provided that can be drawn into a GraphWin. As a
simple example, here is a complete program to draw a circle of radius
10 centered in a 100x100 window:

--------------------------------------------------------------------
from graphics import *

def main():
    win = GraphWin("My Circle", 100, 100)
    c = Circle(Point(50,50), 10)
    c.draw(win)
    win.getMouse() // Pause to view result

main()
--------------------------------------------------------------------
GraphWin objects support coordinate transformation through the
setCoords method and pointer-based input through getMouse.

The library provides the following graphical objects:
    Point
    Line
    Circle
    Oval
    Rectangle
    Polygon
    Text
    Entry (for text-based input)
    Image

Various attributes of graphical objects can be set such as
outline-color, fill-color and line-width. Graphical objects also
support moving and hiding for animation effects.

The library also provides a very simple class for pixel-based image
manipulation, Pixmap. A pixmap can be loaded from a file and displayed
using an Image object. Both getPixel and setPixel methods are provided
for manipulating the image.

DOCUMENTATION: For complete documentation, see Chapter 5 of "Python
Programming: An Introduction to Computer Science" by John Zelle,
published by Franklin, Beedle & Associates.  Also see
http://mcsp.wartburg.edu/zelle/python for a quick referenceiNt
GraphicsErrorcBseZdZedZRS(s3Generic error class for graphics module exceptions.cCs
||_dS(N(targs(tselfR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt__init__s(t__name__t
__module__t__doc__tNoneR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRssObject currently drawns Object doesn't support operationsIllegal option values!Graphics thread quit unexpectedly(tcopy(tQueueiii
cCs4tiatititttidS(N(ttktTkt_roottwithdrawtaftert_POLL_INTERVALt_tk_pumptmainloop(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt
_tk_threads
cCsxttipfti\}}y%|}|oti|nWqta|otidnqXqWtoti	t
tndS(N(t_tk_requesttemptytgett
_tk_resulttputtFalset_thread_runningRRRRR(tcommandt
returns_valuetresult((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs	csRtp
ttnfd}ti|tfttit}|S(Ncs
S(N(((Rtkwtf(s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytfuncs(RRtDEAD_THREADRRtTrueRR(RRRRR((RRRs?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt_tkCalls
csCtp
ttnfd}ti|tftdS(Ncs
S(N(((RRR(s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs(RRR RRRR!(RRRR((RRRs?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt_tkExecs
cCstatiddS(Ng?(RRttimetsleep(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt_tkShutdownstGraphWincBseZdZdddedZdZdZdZdZdZ	d	Z
d
ZdZdd
Z
ddZdZdZdZdZdZdZdZdZdZRS(s8A GraphWin is a toplevel window for displaying graphics.sGraphics WindowicCst|i||||dS(N(R"t_GraphWin__init_help(Rttitletwidththeightt	autoflush((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCstit}|id|itii||d|d||ii||i	|i
ddd|_g|_d|_d|_|id|i||_||_||_d|_d|_t|_|otindS(NtWM_DELETE_WINDOWR*R+itblacks
<Button-1>(R
tToplevelRtprotocolt_GraphWin__close_helptCanvasRtmasterR)tpackt	resizablet
foregroundtitemsRtmouseXtmouseYtbindt_onClickR+R*R,t_mouseCallbackttransRtclosedtupdate(RR)R*R+R,R3((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt__init_helps$
										cCs|io
tdndS(Nswindow is closed(R>R(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt__checkOpens
cCs!|it|id|dS(s"Set background color of the windowtbgN(t_GraphWin__checkOpenR#tconfig(Rtcolor((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt
setBackgrounds
cCs(t|i|i|||||_dS(stSet coordinates of window to run from (x1,y1) in the
        lower-left corner to (x2,y2) in the upper-right corner.N(t	TransformR*R+R=(Rtx1ty1tx2ty2((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt	setCoords	scCs#|iodSnt|idS(N(R>R"R1(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytclosescCs$t|_|iitidS(sClose the windowN(R!R>R3tdestroyRR?(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt__close_helps	
cCs|iS(N(R>(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytisClosedscCs|iottindS(N(R,R"RR?(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt__autoflushs
R.cCsS|i|i||\}}t|i|||d|d||idS(s"Set pixel (x,y) to the given coloritfillN(RCttoScreenR#tcreate_linet_GraphWin__autoflush(RtxtyREtxstys((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytplots
#cCs;|it|i|||d|d||idS(sNSet pixel raw (independent of window coordinates) pixel
        (x,y) to coloriRRN(RCR#RTRU(RRVRWRE((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt	plotPixel's
#cCs|it|idS(sUpdate drawing to the windowN(RCR"tupdate_idletasks(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytflush/s
cCst|_t|_xY|itjp|itjo8t|i|io
tdntidqW|i	|i|i\}}t|_t|_t
||S(sKWait for mouse click and return Point object representing
        the clicksgetMouse in closed windowg?(RR8R9R"R?RPRR$R%ttoWorldtPoint(RRVRW((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytgetMouse5s		#
		cCs|io
tdnt|i|idjoQ|idjoA|i|i|i\}}d|_d|_t||SndSdS(saReturn mouse click last mouse click or None if mouse has
        not been clicked since last callscheckMouse in closed windowN(	RPRR"R?R8RR9R^R_(RRVRW((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt
checkMouseDs


 		cCs|iS(sReturn the height of the window(R+(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt	getHeightRscCs|iS(sReturn the width of the window(R*(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytgetWidthVscCs5|i}|o|ii||Sn||fSdS(N(R=tscreen(RRVRWR=((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRSZs	cCs5|i}|o|ii||Sn||fSdS(N(R=tworld(RRVRWR=((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR^as	cCs
||_dS(N(R<(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytsetMouseHandlerhscCsF|i|_|i|_|io |it|i|indS(N(RVR8RWR9R<R_(Rte((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR;ks
(RRRRRR(RCRFRLRMR1RPRURZR[R]R`RaRbRcRSR^RfR;(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR's,																RGcBs)eZdZdZdZdZRS(s1Internal class for 2-D coordinate transformationsc	CsX||}||}||_||_|t|d|_|t|d|_dS(Ni(txbasetybasetfloattxscaletyscale(	Rtwthtxlowtylowtxhightyhightxspantyspan((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRus

		cCsF||i|i}|i||i}t|dt|dfS(Ng?(RhRkRiRltint(RRVRWRXRY((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRdscCs2||i|i}|i||i}||fS(N(RkRhRiRl(RRXRYRVRW((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRes(RRRRRdRe(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRGqs		tRRR.toutlinet1R*tnonetarrowttexttcentertjustifyt	helveticaitnormaltfonttGraphicsObjectcBsheZdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZRS(s2Generic base class for all of the drawable objectscCsDd|_d|_h}x|D]}t|||<qW||_dS(N(RtcanvastidtDEFAULT_CONFIGRD(RtoptionsRDtoption((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs		cCs|id|dS(sSet interior color to colorRRN(t	_reconfig(RRE((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytsetFillscCs|id|dS(sSet outline color to colorRwN(R(RRE((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt
setOutlinescCs|id|dS(sSet line weight to widthR*N(R(RR*((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytsetWidthscCs|io|iio
ttn|io
tdn||_t|i||i|_|iott	i
ndS(sDraw the object in graphwin, which should be a GraphWin
        object.  A GraphicsObject may only be drawn into one
        window. Raises an error if attempt made to draw an object that
        is already visible.sCan't draw to closed windowN(RRPRtOBJ_ALREADY_DRAWNR"t_drawRDRR,RR?(Rtgraphwin((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytdraws(	
cCsp|ipdSn|iip8t|ii|i|iiottiqZnd|_d|_dS(s`Undraw the object (i.e. hide it). Returns silently if the
        object is not currently drawn.N(
RRPR#tdeleteRR,R"RR?R(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytundraws
	cCs|i|||i}|o|iov|i}|o||i}||i}n
|}|}t|ii|i|||i	ot
tiqndS(sGmove object dx units in x direction and dy units in y
        directionN(
t_moveRRPR=RkRlR#tmoveRR,R"RR?(RtdxtdyRR=RVRW((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs		

cCs|ii|p
ttn|i}|||<|ioL|iio;t|ii|i||ii	ot
tiqndS(N(
RDthas_keyRtUNSUPPORTED_METHODRRPR#t
itemconfigRR,R"RR?(RRtsettingR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs
	

cCsdS(s\draws appropriate figure on canvas with options provided
        Returns Tk id of item drawnN((RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCsdS(s7updates internal state of object to move it dx,dy unitsN((RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs(
RRRRRRRRRRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs									R_cBs>eZdZdZdZdZdZdZRS(cCs8ti|ddg|i|_||_||_dS(NRwRR(RRRRRVRW(RRVRW((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs	cCs?|i|i|i\}}|i|||d|d|S(Ni(RSRVRWtcreate_rectangle(RRRRVRW((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCs$|i||_|i||_dS(N(RVRW(RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCs+t|i|i}|ii|_|S(N(R_RVRWRDR(Rtother((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytclonescCs|iS(N(RV(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytgetXscCs|iS(N(RW(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytgetYs(RRRRRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR_s					t_BBoxcBsAeZdddgdZdZdZdZdZRS(RwR*RRcCs2ti|||i|_|i|_dS(N(RRRtp1tp2(RRRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR scCs\|ii||i_|ii||i_|ii||i_|ii||i_dS(N(RRVRWR(RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR%scCs
|iiS(N(RR(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytgetP1+scCs
|iiS(N(RR(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytgetP2-scCs;|i}|i}t|i|id|i|idS(Ng@(RRR_RVRW(RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt	getCenter/s		(RRRRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs
			t	RectanglecBs#eZdZdZdZRS(cCsti|||dS(N(RR(RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR6sc	Csg|i}|i}|i|i|i\}}|i|i|i\}}|i|||||S(N(RRRSRVRWR(	RRRRRRHRIRJRK((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR9s
		cCs+t|i|i}|ii|_|S(N(RRRRDR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR@s(RRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR4s		tOvalcBs#eZdZdZdZRS(cCsti|||dS(N(RR(RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRGscCs+t|i|i}|ii|_|S(N(RRRRDR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRJsc	Csg|i}|i}|i|i|i\}}|i|i|i\}}|i|||||S(N(RRRSRVRWtcreate_oval(	RRRRRRHRIRJRK((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyROs
		(RRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyREs		tCirclecBs#eZdZdZdZRS(cCsZt|i||i|}t|i||i|}ti|||||_dS(N(R_RVRWRRtradius(RR|RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRXscCs.t|i|i}|ii|_|S(N(RRRRDR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR^scCs|iS(N(R(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt	getRadiuscs(RRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRVs		tLinecBs,eZdZdZdZdZRS(cCs@ti|||dddg|itd|i|_dS(NRzRRR*Rw(RRRRR(RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRhscCs+t|i|i}|ii|_|S(N(RRRRDR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRmsc	Csg|i}|i}|i|i|i\}}|i|i|i\}}|i|||||S(N(RRRSRVRWRT(	RRRRRRHRIRJRK((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRrs
		cCs.|djo
ttn|id|dS(NtfirsttlasttbothRyRz(RRRRy(Rt
BAD_OPTIONR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytsetArrowys

(RRRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRfs			tPolylinecBs5eZdZdZdZdZdZRS(cGst|djo+t|dtgjo|d}ntti||_g}|iD]
}||qa~|_|ii|ii|it	i
|dddgdS(NiiRwR*RR(tlenttypetmapR_Rtpointst	revpointstreversetextendRR(RRt_[1]RV((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs0'
cCs(tt|i}|ii|_|S(N(tapplyRRRDR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCs'tti|idt|id!S(Nii(RR_RRR(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt	getPointsscCs(x!|iD]}|i||q
WdS(N(RR(RRRtp((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs
cCsr|g}xI|iD]>}|i|i|i\}}|i||i|qW|i|tti|S(N(RRSRVRWtappendRR'tcreate_polygon(RRRRRRVRW((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs	


(RRRRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs
				tPolygoncBs5eZdZdZdZdZdZRS(cGspt|djo+t|dtgjo|d}ntti||_ti|dddgdS(NiiRwR*RR(RRRR_RRRR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs0cCs(tt|i}|ii|_|S(N(RRRRDR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCstti|iS(N(RR_RR(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCs(x!|iD]}|i||q
WdS(N(RR(RRRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs
cCsr|g}xI|iD]>}|i|i|i\}}|i||i|qW|i|tti|S(N(RRSRVRWRRR'R(RRRRRRVRW((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs	


(RRRRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs
				tTextcBskeZdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZRS(cCsYti|ddddg|i||i|_|itd|i|_dS(NR}RRR{RRw(RRtsetTextRtanchorRRR(RRR{((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs

cCs:|i}|i|i|i\}}|i|||S(N(RRSRVRWtcreate_text(RRRRRVRW((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs	cCs|ii||dS(N(RR(RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCs/t|i|id}|ii|_|S(NR{(RRRDR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCs|id|dS(NR{(R(RR{((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCs|idS(NR{(RD(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytgetTextscCs
|iiS(N(RR(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt	getAnchorscCsM|djo3|id\}}}|id|||fn
ttdS(NR~tarialtcourierstimes romanR(R~RRstimes roman(RDRRR(RtfaceRtstb((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytsetFaces
cCs^d|jo
djno3|id\}}}|id|||fn
ttdS(Nii$R(RDRRR(RtsizeRRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytsetSizescCsM|djo3|id\}}}|id|||fn
ttdS(NtboldRtitalicsbold italicR(RRRsbold italic(RDRRR(RtstyleRRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytsetStyles
cCs|i|dS(N(R(RRE((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytsetTextColors(
RRRRRRRRRRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs										tEntrycBseZdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZ
dZd
ZRS(cCs|ti|g|i|_||_ttit|_	t|i	i
dd|_d|_t
d|_d|_dS(NRvtgrayR.R(RRRRR*R"R
t	StringVarRR{tsetRRRERRRtentry(RRR*((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs			
cCs|i}|i|i|i\}}ti|i}ti|d|id|i	d|i
d|id|i|_
|i
i|i||d|S(NR*ttextvariableRBtfgRtwindow(RRSRVRWR
tFrameR3RR*R{RRRERRR4t
create_window(RRRRRVRWtfrm((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs					
cCst|iiS(N(R"R{R(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCs|ii||dS(N(RR(RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCs
|iiS(N(RR(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR scCs%t|i|i}t|i|S(N(RRR*R"t_Entry__clone_help(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR#scCsJ|ii|_ti|_|ii|ii|i|_|S(N(RDRR
RR{RRRR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt__clone_help's
cCst|ii|dS(N(R"R{R(Rtt((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR.scCs1||_|iot|iid|ndS(NRB(RRRR#RD(RRE((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR2s	
cCsSt|i}|||<t||_|iot|iid|indS(NR(tlistRttupleRR#RD(RtwhichtvalueR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyt_setFontComponent8s


cCs.|djo|id|n
ttdS(NR~RRstimes romani(s	helveticasarialscourierstimes roman(RRR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR@s
cCs?d|jo
djno|id|n
ttdS(Nii$i(RRR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRFscCs.|djo|id|n
ttdS(NRRRsbold italici(sboldsnormalsitalicsbold italic(RRR(RR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRLs
cCs1||_|iot|iid|ndS(NR(RERR#RD(RRE((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRRs	
(RRRRRRRRRRRRRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs													tImagecBsJeZdZhZdZdZdZdZdZdZ	RS(icCsti|g|i|_ti|_tidt_t|tdjoti	d|dt
|_n
|i|_dS(NiRvtfileR3(
RRRRRtidCounttimageIdRR
t
PhotoImageRtimgtimage(RRtpixmap((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyR^scCsS|i}|i|i|i\}}|i|i|i<|i||d|iS(NR(RRSRVRWRt
imageCacheRtcreate_image(RRRRRVRW((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRhs	cCs|ii||dS(N(RR(RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRnscCs|i|i=ti|dS(N(RRRR(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRqs
cCs
|iiS(N(RR(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRuscCs@tt|ii}t|i|}|ii|_|S(N(tPixmapR"RRRRRD(RtimgCopyR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRxs(
RRRRRRRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRYs	
				RcBsMeZdZdZdZdZdZdZdZdZ	RS(sPixmap represents an image as a 2D array of color values.
    A Pixmap can be made from a file (gif or ppm):

       pic = Pixmap("myPicture.gif")
       
    or initialized to a given size (initially transparent):

       pic = Pixmap(512, 512)


    cGst|djoTt|dtdjo&ttid|ddt|_q|d|_n1|\}}ttidtd|d||_dS(NiiRvRR3R*R+(RRR"R
RRR(RRR*R+((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs&cCst|iiS(s(Returns the width of the image in pixels(R"RR*(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRcscCst|iiS(s)Returns the height of the image in pixels(R"RR+(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRbscCsSt|ii||}t|tjo|||gSntt|iSdS(sjReturns a list [r,g,b] with the RGB color values for pixel (x,y)
        r,g,b are in range(256)

        N(R"RRRRuRtsplit(RRVRWR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytgetPixelscCs?|\}}}t|iidt|||||fdS(snSets pixel (x,y) to the color given by RGB values r, g, and b.
        r,g,b should be in range(256)

        s{%s}N(R#RRt	color_rgb(RRVRWt.3trtgR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytsetPixelscCst|iiS(sReturns a copy of this Pixmap(RRR(R((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCsHtii|\}}|idd}t|ii|d|dS(s}Saves the pixmap image to filename.
        The format for the save image is determined from the filname extension.

        t.itformatN(tostpathRR#Rtwrite(RtfilenameRtnametext((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pytsaves(
RRRRRcRbRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRs					
	cCsd|||fS(svr,g,b are intensities of red, green, and blue in range(256)
    Returns color specifier string for the resulting colors
#%02x%02x%02x((RRR((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyRscCsut}|iddddttddd}|i|ttddtddtdd}|i|ttdd	d}|i||i|id
|i	d|i
dd}x4|iD]&}|d
|i|i
f}qW|i|i|id|id|idd|i|iddd}x4|iD]&}|d
|i|i
f}q{W|i||i|i|i|id|i|id|i|id|i|id|i|id|i|id|id|i|idS(Nii
is
Centered TextiiiiitredtblueRvs(%0.1f,%0.1f) tgreensSpam!RRRsbold italiciRi(R'RLRR_RRRR`RRRRRRRRRRRRRRM(twinRRRgRtpt((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pyttestsX	
-






$



$
















t__main__(((s	helveticaisnormal(((4RR$RtsystTkinterR
t
exceptionst	ExceptionRRRRR RR	tthreadtatexitRRRRRR!Rt_exception_infoRRR"R#R&tstart_new_threadtregisterR2R'RGRRR_RRRRRRRRRRRRRR(((s?/csdept/home/www/users/sprenkle/cs111/examples/1029/graphics.pys<module><sh@$			
	
	

					n'8]&G		,


rectangle.py 8/11

[
top][prev][next]
# Using the Graphics Library
# by Sara Sprenkle, 10.29.2007

from graphics import *

win = GraphWin()

upperleft = Point(5, 10)
lowerright = Point(50, 60)

rect = Rectangle(upperleft, lowerright)

rect.draw(win)

rect.move(10,0)

upperleft = rect.getP1()

print "The upperleft corner of the rectangle is at (",
print upperleft.getX(), ",", upperleft.getY(), ")"

win.getMouse()

tictactoe2.py 9/11

[
top][prev][next]
# Demonstrate drawing a full-canvas tic-tac-toe board
# by Sara Sprenkle, 10.29.07

from graphics import *

COLOR="purple"

def main() :

    win = GraphWin("TIC-TAC-TOE Board", 500, 500)

    drawTictactoe(win)
    
    # Pause so user can see the result
    win.getMouse()


# Input: canvas, a GraphWin object
# Postcondition: canvas has a full-screen tic-tac-toe board drawn on
# it
def drawTictactoe(canvas):
    width = canvas.getWidth()
    height = canvas.getHeight()
    
    topPoint = Point(width/3, 0)
    bottomPoint = Point(width/3, height)

    leftPoint = Point(0, height/3)
    rightPoint = Point(width, height/3)
    
    # draw the vertical lines
    line = Line(topPoint, bottomPoint)
    line.setOutline(COLOR)
    line.setWidth(3)
    line.draw(canvas)

    vline = line.clone()
    vline.move(width/3,0)
    vline.draw(canvas)

    # draw the horizontal lines
    line = Line(leftPoint, rightPoint)
    line.setOutline(COLOR)
    line.setWidth(3)
    line.draw(canvas)

    hline = line.clone()
    hline.move(0,height/3)
    hline.draw(canvas)


main()


tictactoe.py 10/11

[
top][prev][next]
# Demonstrate drawing a full-canvas tic-tac-toe board
# by Sara Sprenkle, 10.29.07

from graphics import *

COLOR="purple"

def main() :

    win = GraphWin("TIC-TAC-TOE Board", 500, 500)

    drawTictactoe(win)
    
    # Pause so user can see the result
    win.getMouse()


# Input: canvas, a GraphWin object
# Postcondition: canvas has a full-screen tic-tac-toe board drawn on
# it
def drawTictactoe(canvas):
    width = canvas.getWidth()
    height = canvas.getHeight()
    
    topPoint1 = Point(width/3, 0)
    topPoint2 = Point(2*width/3, 0)
    bottomPoint1 = Point(width/3, height)
    bottomPoint2 = Point(2*width/3, height)

    leftPoint1 = Point(0, height/3)
    leftPoint2 = Point(0, 2*height/3)
    rightPoint1 = Point(width, height/3)
    rightPoint2 = Point(width, 2*height/3)
    
    # draw the vertical lines
    line = Line(topPoint1, bottomPoint1)
    line.setOutline(COLOR)
    line.setWidth(3)
    line.draw(canvas)

    line = Line(topPoint2, bottomPoint2)
    line.setOutline(COLOR)
    line.setWidth(3)
    line.draw(canvas)

    # draw the horizontal lines
    line = Line(leftPoint1, rightPoint1)
    line.setOutline(COLOR)
    line.setWidth(3)
    line.draw(canvas)

    line = Line(leftPoint2, rightPoint2)
    line.setOutline(COLOR)
    line.setWidth(3)
    line.draw(canvas)

main()


userDraw.py 11/11

[
top][prev][next]
# Demonstrate getting user input with GraphWin.getMouse()
# by Sara Sprenkle, 10.29.07

from graphics import *

win = GraphWin("Drawing", 500, 500)

text = Text( Point(250,450), "Click where you want the first point.")
text.draw(win)

# get the user's mouse click
pt1 = win.getMouse()
pt1.draw(win)

text.setText("Click where you want the second point.")

# get the user's second mouse click
pt2 = win.getMouse()
pt2.draw(win)

# draw the line
text.setText("Here is your line!")
line = Line(pt1, pt2)
line.setOutline("purple")
line.setWidth(3)
line.draw(win)

# Pause so user can see the result
win.getMouse() 


Generated by GNU enscript 1.6.4.