Advertisement
here2share

# Tk_graphics_help.py

Sep 18th, 2016
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 31.81 KB | None | 0 0
  1. # Tk_graphics_help.py
  2. """Simple object oriented graphics library  
  3.  
  4. The library is designed to make it very easy for novice programmers to
  5. experiment with computer graphics in an object oriented fashion. It is
  6. written by John Zelle for use with the book "Python Programming: An
  7. Introduction to Computer Science" (Franklin, Beedle & Associates).
  8.  
  9. LICENSE: This is open-source software released under the terms of the
  10. GPL (http://www.gnu.org/licenses/gpl.html).
  11.  
  12. PLATFORMS: The package is a wrapper around Tkinter and should run on
  13. any platform where Tkinter is available.
  14.  
  15. INSTALLATION: Put this file somewhere where Python can see it.
  16.  
  17. OVERVIEW: There are two kinds of objects in the library. The GraphWin
  18. class implements a window where drawing can be done and various
  19. GraphicsObjects are provided that can be drawn into a GraphWin. As a
  20. simple example, here is a complete program to draw a circle of radius
  21. 10 centered in a 100x100 window:
  22.  
  23. --------------------------------------------------------------------
  24. from graphics import *
  25.  
  26. def main():
  27.    win = GraphWin("My Circle", 100, 100)
  28.    c = Circle(Point(50,50), 10)
  29.    c.draw(win)
  30.    win.getMouse() # Pause to view result
  31.    win.close()    # Close window when done
  32.  
  33. main()
  34. --------------------------------------------------------------------
  35. GraphWin objects support coordinate transformation through the
  36. setCoords method and mouse and keyboard interaction methods.
  37.  
  38. The library provides the following graphical objects:
  39.    Point
  40.    Line
  41.    Circle
  42.    Oval
  43.    Rectangle
  44.    Polygon
  45.    Text
  46.    Entry (for text-based input)
  47.    Image
  48.  
  49. Various attributes of graphical objects can be set such as
  50. outline-color, fill-color and line-width. Graphical objects also
  51. support moving and hiding for animation effects.
  52.  
  53. The library also provides a very simple class for pixel-based image
  54. manipulation, Pixmap. A pixmap can be loaded from a file and displayed
  55. using an Image object. Both getPixel and setPixel methods are provided
  56. for manipulating the image.
  57.  
  58. DOCUMENTATION: For complete documentation, see Chapter 4 of "Python
  59. Programming: An Introduction to Computer Science" by John Zelle,
  60. published by Franklin, Beedle & Associates.  Also see
  61. http://mcsp.wartburg.edu/zelle/python for a quick reference"""
  62.  
  63. __version__ = "5.0"
  64.  
  65. # Version 5 8/26/2016
  66. #     * update at bottom to fix MacOS issue causing askopenfile() to hang
  67. #     * update takes an optional parameter specifying update rate
  68. #     * Entry objects get focus when drawn
  69. #     * __repr_ for all objects
  70. #     * fixed offset problem in window, made canvas borderless
  71.  
  72. # Version 4.3 4/25/2014
  73. #     * Fixed Image getPixel to work with Python 3.4, TK 8.6 (tuple type handling)
  74. #     * Added interactive keyboard input (getKey and checkKey) to GraphWin
  75. #     * Modified setCoords to cause redraw of current objects, thus
  76. #       changing the view. This supports scrolling around via setCoords.
  77. #
  78. # Version 4.2 5/26/2011
  79. #     * Modified Image to allow multiple undraws like other GraphicsObjects
  80. # Version 4.1 12/29/2009
  81. #     * Merged Pixmap and Image class. Old Pixmap removed, use Image.
  82. # Version 4.0.1 10/08/2009
  83. #     * Modified the autoflush on GraphWin to default to True
  84. #     * Autoflush check on close, setBackground
  85. #     * Fixed getMouse to flush pending clicks at entry
  86. # Version 4.0 08/2009
  87. #     * Reverted to non-threaded version. The advantages (robustness,
  88. #         efficiency, ability to use with other Tk code, etc.) outweigh
  89. #         the disadvantage that interactive use with IDLE is slightly more
  90. #         cumbersome.
  91. #     * Modified to run in either Python 2.x or 3.x (same file).
  92. #     * Added Image.getPixmap()
  93. #     * Added update() -- stand alone function to cause any pending
  94. #           graphics changes to display.
  95. #
  96. # Version 3.4 10/16/07
  97. #     Fixed GraphicsError to avoid "exploded" error messages.
  98. # Version 3.3 8/8/06
  99. #     Added checkMouse method to GraphWin
  100. # Version 3.2.3
  101. #     Fixed error in Polygon init spotted by Andrew Harrington
  102. #     Fixed improper threading in Image constructor
  103. # Version 3.2.2 5/30/05
  104. #     Cleaned up handling of exceptions in Tk thread. The graphics package
  105. #     now raises an exception if attempt is made to communicate with
  106. #     a dead Tk thread.
  107. # Version 3.2.1 5/22/05
  108. #     Added shutdown function for tk thread to eliminate race-condition
  109. #        error "chatter" when main thread terminates
  110. #     Renamed various private globals with _
  111. # Version 3.2 5/4/05
  112. #     Added Pixmap object for simple image manipulation.
  113. # Version 3.1 4/13/05
  114. #     Improved the Tk thread communication so that most Tk calls
  115. #        do not have to wait for synchonization with the Tk thread.
  116. #        (see _tkCall and _tkExec)
  117. # Version 3.0 12/30/04
  118. #     Implemented Tk event loop in separate thread. Should now work
  119. #        interactively with IDLE. Undocumented autoflush feature is
  120. #        no longer necessary. Its default is now False (off). It may
  121. #        be removed in a future version.
  122. #     Better handling of errors regarding operations on windows that
  123. #       have been closed.
  124. #     Addition of an isClosed method to GraphWindow class.
  125.  
  126. # Version 2.2 8/26/04
  127. #     Fixed cloning bug reported by Joseph Oldham.
  128. #     Now implements deep copy of config info.
  129. # Version 2.1 1/15/04
  130. #     Added autoflush option to GraphWin. When True (default) updates on
  131. #        the window are done after each action. This makes some graphics
  132. #        intensive programs sluggish. Turning off autoflush causes updates
  133. #        to happen during idle periods or when flush is called.
  134. # Version 2.0
  135. #     Updated Documentation
  136. #     Made Polygon accept a list of Points in constructor
  137. #     Made all drawing functions call TK update for easier animations
  138. #          and to make the overall package work better with
  139. #          Python 2.3 and IDLE 1.0 under Windows (still some issues).
  140. #     Removed vestigial turtle graphics.
  141. #     Added ability to configure font for Entry objects (analogous to Text)
  142. #     Added setTextColor for Text as an alias of setFill
  143. #     Changed to class-style exceptions
  144. #     Fixed cloning of Text objects
  145.  
  146. # Version 1.6
  147. #     Fixed Entry so StringVar uses _root as master, solves weird
  148. #            interaction with shell in Idle
  149. #     Fixed bug in setCoords. X and Y coordinates can increase in
  150. #           "non-intuitive" direction.
  151. #     Tweaked wm_protocol so window is not resizable and kill box closes.
  152.  
  153. # Version 1.5
  154. #     Fixed bug in Entry. Can now define entry before creating a
  155. #     GraphWin. All GraphWins are now toplevel windows and share
  156. #     a fixed root (called _root).
  157.  
  158. # Version 1.4
  159. #     Fixed Garbage collection of Tkinter images bug.
  160. #     Added ability to set text atttributes.
  161. #     Added Entry boxes.
  162.  
  163. import time, os, sys
  164.  
  165. try:  # import as appropriate for 2.x vs. 3.x
  166.    import tkinter as tk
  167. except:
  168.    import Tkinter as tk
  169.  
  170.  
  171. ##########################################################################
  172. # Module Exceptions
  173.  
  174. class GraphicsError(Exception):
  175.     """Generic error class for graphics module exceptions."""
  176.     pass
  177.  
  178. OBJ_ALREADY_DRAWN = "Object currently drawn"
  179. UNSUPPORTED_METHOD = "Object doesn't support operation"
  180. BAD_OPTION = "Illegal option value"
  181.  
  182. ##########################################################################
  183. # global variables and funtions
  184.  
  185. _root = tk.Tk()
  186. _root.withdraw()
  187.  
  188. _update_lasttime = time.time()
  189.  
  190. def update(rate=None):
  191.     global _update_lasttime
  192.     if rate:
  193.         now = time.time()
  194.         pauseLength = 1/rate-(now-_update_lasttime)
  195.         if pauseLength > 0:
  196.             time.sleep(pauseLength)
  197.             _update_lasttime = now + pauseLength
  198.         else:
  199.             _update_lasttime = now
  200.  
  201.     _root.update()
  202.  
  203. ############################################################################
  204. # Graphics classes start here
  205.        
  206. class GraphWin(tk.Canvas):
  207.  
  208.     """A GraphWin is a toplevel window for displaying graphics."""
  209.  
  210.     def __init__(self, title="Graphics Window",
  211.                  width=200, height=200, autoflush=True):
  212.         assert type(title) == type(""), "Title must be a string"
  213.         master = tk.Toplevel(_root)
  214.         master.protocol("WM_DELETE_WINDOW", self.close)
  215.         tk.Canvas.__init__(self, master, width=width, height=height,
  216.                            highlightthickness=0, bd=0)
  217.         self.master.title(title)
  218.         self.pack()
  219.         master.resizable(0,0)
  220.         self.foreground = "black"
  221.         self.items = []
  222.         self.mouseX = None
  223.         self.mouseY = None
  224.         self.bind("<Button-1>", self._onClick)
  225.         self.bind_all("<Key>", self._onKey)
  226.         self.height = int(height)
  227.         self.width = int(width)
  228.         self.autoflush = autoflush
  229.         self._mouseCallback = None
  230.         self.trans = None
  231.         self.closed = False
  232.         master.lift()
  233.         self.lastKey = ""
  234.         if autoflush: _root.update()
  235.  
  236.     def __repr__(self):
  237.         if self.isClosed():
  238.             return "<Closed GraphWin>"
  239.         else:
  240.             return "GraphWin('{}', {}, {})".format(self.master.title(),
  241.                                              self.getWidth(),
  242.                                              self.getHeight())
  243.  
  244.     def __str__(self):
  245.         return repr(self)
  246.      
  247.     def __checkOpen(self):
  248.         if self.closed:
  249.             raise GraphicsError("window is closed")
  250.  
  251.     def _onKey(self, evnt):
  252.         self.lastKey = evnt.keysym
  253.  
  254.  
  255.     def setBackground(self, color):
  256.         """Set background color of the window"""
  257.         self.__checkOpen()
  258.         self.config(bg=color)
  259.         self.__autoflush()
  260.        
  261.     def setCoords(self, x1, y1, x2, y2):
  262.         """Set coordinates of window to run from (x1,y1) in the
  263.        lower-left corner to (x2,y2) in the upper-right corner."""
  264.         self.trans = Transform(self.width, self.height, x1, y1, x2, y2)
  265.         self.redraw()
  266.  
  267.     def close(self):
  268.         """Close the window"""
  269.  
  270.         if self.closed: return
  271.         self.closed = True
  272.         self.master.destroy()
  273.         self.__autoflush()
  274.  
  275.  
  276.     def isClosed(self):
  277.         return self.closed
  278.  
  279.  
  280.     def isOpen(self):
  281.         return not self.closed
  282.  
  283.  
  284.     def __autoflush(self):
  285.         if self.autoflush:
  286.             _root.update()
  287.  
  288.    
  289.     def plot(self, x, y, color="black"):
  290.         """Set pixel (x,y) to the given color"""
  291.         self.__checkOpen()
  292.         xs,ys = self.toScreen(x,y)
  293.         self.create_line(xs,ys,xs+1,ys, fill=color)
  294.         self.__autoflush()
  295.        
  296.     def plotPixel(self, x, y, color="black"):
  297.         """Set pixel raw (independent of window coordinates) pixel
  298.        (x,y) to color"""
  299.         self.__checkOpen()
  300.         self.create_line(x,y,x+1,y, fill=color)
  301.         self.__autoflush()
  302.      
  303.     def flush(self):
  304.         """Update drawing to the window"""
  305.         self.__checkOpen()
  306.         self.update_idletasks()
  307.        
  308.     def getMouse(self):
  309.         """Wait for mouse click and return Point object representing
  310.        the click"""
  311.         self.update()      # flush any prior clicks
  312.         self.mouseX = None
  313.         self.mouseY = None
  314.         while self.mouseX == None or self.mouseY == None:
  315.             self.update()
  316.             if self.isClosed(): raise GraphicsError("getMouse in closed window")
  317.             time.sleep(.1) # give up thread
  318.         x,y = self.toWorld(self.mouseX, self.mouseY)
  319.         self.mouseX = None
  320.         self.mouseY = None
  321.         return Point(x,y)
  322.  
  323.     def checkMouse(self):
  324.         """Return last mouse click or None if mouse has
  325.        not been clicked since last call"""
  326.         if self.isClosed():
  327.             raise GraphicsError("checkMouse in closed window")
  328.         self.update()
  329.         if self.mouseX != None and self.mouseY != None:
  330.             x,y = self.toWorld(self.mouseX, self.mouseY)
  331.             self.mouseX = None
  332.             self.mouseY = None
  333.             return Point(x,y)
  334.         else:
  335.             return None
  336.  
  337.     def getKey(self):
  338.         """Wait for user to press a key and return it as a string."""
  339.         self.lastKey = ""
  340.         while self.lastKey == "":
  341.             self.update()
  342.             if self.isClosed(): raise GraphicsError("getKey in closed window")
  343.             time.sleep(.1) # give up thread
  344.  
  345.         key = self.lastKey
  346.         self.lastKey = ""
  347.         return key
  348.  
  349.     def checkKey(self):
  350.         """Return last key pressed or None if no key pressed since last call"""
  351.         if self.isClosed():
  352.             raise GraphicsError("checkKey in closed window")
  353.         self.update()
  354.         key = self.lastKey
  355.         self.lastKey = ""
  356.         return key
  357.            
  358.     def getHeight(self):
  359.         """Return the height of the window"""
  360.         return self.height
  361.        
  362.     def getWidth(self):
  363.         """Return the width of the window"""
  364.         return self.width
  365.    
  366.     def toScreen(self, x, y):
  367.         trans = self.trans
  368.         if trans:
  369.             return self.trans.screen(x,y)
  370.         else:
  371.             return x,y
  372.                      
  373.     def toWorld(self, x, y):
  374.         trans = self.trans
  375.         if trans:
  376.             return self.trans.world(x,y)
  377.         else:
  378.             return x,y
  379.        
  380.     def setMouseHandler(self, func):
  381.         self._mouseCallback = func
  382.        
  383.     def _onClick(self, e):
  384.         self.mouseX = e.x
  385.         self.mouseY = e.y
  386.         if self._mouseCallback:
  387.             self._mouseCallback(Point(e.x, e.y))
  388.  
  389.     def addItem(self, item):
  390.         self.items.append(item)
  391.  
  392.     def delItem(self, item):
  393.         self.items.remove(item)
  394.  
  395.     def redraw(self):
  396.         for item in self.items[:]:
  397.             item.undraw()
  398.             item.draw(self)
  399.         self.update()
  400.        
  401.                      
  402. class Transform:
  403.  
  404.     """Internal class for 2-D coordinate transformations"""
  405.    
  406.     def __init__(self, w, h, xlow, ylow, xhigh, yhigh):
  407.         # w, h are width and height of window
  408.         # (xlow,ylow) coordinates of lower-left [raw (0,h-1)]
  409.         # (xhigh,yhigh) coordinates of upper-right [raw (w-1,0)]
  410.         xspan = (xhigh-xlow)
  411.         yspan = (yhigh-ylow)
  412.         self.xbase = xlow
  413.         self.ybase = yhigh
  414.         self.xscale = xspan/float(w-1)
  415.         self.yscale = yspan/float(h-1)
  416.        
  417.     def screen(self,x,y):
  418.         # Returns x,y in screen (actually window) coordinates
  419.         xs = (x-self.xbase) / self.xscale
  420.         ys = (self.ybase-y) / self.yscale
  421.         return int(xs+0.5),int(ys+0.5)
  422.        
  423.     def world(self,xs,ys):
  424.         # Returns xs,ys in world coordinates
  425.         x = xs*self.xscale + self.xbase
  426.         y = self.ybase - ys*self.yscale
  427.         return x,y
  428.  
  429.  
  430. # Default values for various item configuration options. Only a subset of
  431. #   keys may be present in the configuration dictionary for a given item
  432. DEFAULT_CONFIG = {"fill":"",
  433.       "outline":"black",
  434.       "width":"1",
  435.       "arrow":"none",
  436.       "text":"",
  437.       "justify":"center",
  438.                   "font": ("helvetica", 12, "normal")}
  439.  
  440. class GraphicsObject:
  441.  
  442.     """Generic base class for all of the drawable objects"""
  443.     # A subclass of GraphicsObject should override _draw and
  444.     #   and _move methods.
  445.    
  446.     def __init__(self, options):
  447.         # options is a list of strings indicating which options are
  448.         # legal for this object.
  449.        
  450.         # When an object is drawn, canvas is set to the GraphWin(canvas)
  451.         #    object where it is drawn and id is the TK identifier of the
  452.         #    drawn shape.
  453.         self.canvas = None
  454.         self.id = None
  455.  
  456.         # config is the dictionary of configuration options for the widget.
  457.         config = {}
  458.         for option in options:
  459.             config[option] = DEFAULT_CONFIG[option]
  460.         self.config = config
  461.        
  462.     def setFill(self, color):
  463.         """Set interior color to color"""
  464.         self._reconfig("fill", color)
  465.        
  466.     def setOutline(self, color):
  467.         """Set outline color to color"""
  468.         self._reconfig("outline", color)
  469.        
  470.     def setWidth(self, width):
  471.         """Set line weight to width"""
  472.         self._reconfig("width", width)
  473.  
  474.     def draw(self, graphwin):
  475.  
  476.         """Draw the object in graphwin, which should be a GraphWin
  477.        object.  A GraphicsObject may only be drawn into one
  478.        window. Raises an error if attempt made to draw an object that
  479.        is already visible."""
  480.  
  481.         if self.canvas and not self.canvas.isClosed(): raise GraphicsError(OBJ_ALREADY_DRAWN)
  482.         if graphwin.isClosed(): raise GraphicsError("Can't draw to closed window")
  483.         self.canvas = graphwin
  484.         self.id = self._draw(graphwin, self.config)
  485.         graphwin.addItem(self)
  486.         if graphwin.autoflush:
  487.             _root.update()
  488.         return self
  489.  
  490.            
  491.     def undraw(self):
  492.  
  493.         """Undraw the object (i.e. hide it). Returns silently if the
  494.        object is not currently drawn."""
  495.        
  496.         if not self.canvas: return
  497.         if not self.canvas.isClosed():
  498.             self.canvas.delete(self.id)
  499.             self.canvas.delItem(self)
  500.             if self.canvas.autoflush:
  501.                 _root.update()
  502.         self.canvas = None
  503.         self.id = None
  504.  
  505.  
  506.     def move(self, dx, dy):
  507.  
  508.         """move object dx units in x direction and dy units in y
  509.        direction"""
  510.        
  511.         self._move(dx,dy)
  512.         canvas = self.canvas
  513.         if canvas and not canvas.isClosed():
  514.             trans = canvas.trans
  515.             if trans:
  516.                 x = dx/ trans.xscale
  517.                 y = -dy / trans.yscale
  518.             else:
  519.                 x = dx
  520.                 y = dy
  521.             self.canvas.move(self.id, x, y)
  522.             if canvas.autoflush:
  523.                 _root.update()
  524.            
  525.     def _reconfig(self, option, setting):
  526.         # Internal method for changing configuration of the object
  527.         # Raises an error if the option does not exist in the config
  528.         #    dictionary for this object
  529.         if option not in self.config:
  530.             raise GraphicsError(UNSUPPORTED_METHOD)
  531.         options = self.config
  532.         options[option] = setting
  533.         if self.canvas and not self.canvas.isClosed():
  534.             self.canvas.itemconfig(self.id, options)
  535.             if self.canvas.autoflush:
  536.                 _root.update()
  537.  
  538.  
  539.     def _draw(self, canvas, options):
  540.         """draws appropriate figure on canvas with options provided
  541.        Returns Tk id of item drawn"""
  542.         pass # must override in subclass
  543.  
  544.  
  545.     def _move(self, dx, dy):
  546.         """updates internal state of object to move it dx,dy units"""
  547.         pass # must override in subclass
  548.  
  549.          
  550. class Point(GraphicsObject):
  551.     def __init__(self, x, y):
  552.         GraphicsObject.__init__(self, ["outline", "fill"])
  553.         self.setFill = self.setOutline
  554.         self.x = float(x)
  555.         self.y = float(y)
  556.  
  557.     def __repr__(self):
  558.         return "Point({}, {})".format(self.x, self.y)
  559.        
  560.     def _draw(self, canvas, options):
  561.         x,y = canvas.toScreen(self.x,self.y)
  562.         return canvas.create_rectangle(x,y,x+1,y+1,options)
  563.        
  564.     def _move(self, dx, dy):
  565.         self.x = self.x + dx
  566.         self.y = self.y + dy
  567.        
  568.     def clone(self):
  569.         other = Point(self.x,self.y)
  570.         other.config = self.config.copy()
  571.         return other
  572.                
  573.     def getX(self): return self.x
  574.     def getY(self): return self.y
  575.  
  576. class _BBox(GraphicsObject):
  577.     # Internal base class for objects represented by bounding box
  578.     # (opposite corners) Line segment is a degenerate case.
  579.    
  580.     def __init__(self, p1, p2, options=["outline","width","fill"]):
  581.         GraphicsObject.__init__(self, options)
  582.         self.p1 = p1.clone()
  583.         self.p2 = p2.clone()
  584.  
  585.     def _move(self, dx, dy):
  586.         self.p1.x = self.p1.x + dx
  587.         self.p1.y = self.p1.y + dy
  588.         self.p2.x = self.p2.x + dx
  589.         self.p2.y = self.p2.y  + dy
  590.                
  591.     def getP1(self): return self.p1.clone()
  592.  
  593.     def getP2(self): return self.p2.clone()
  594.    
  595.     def getCenter(self):
  596.         p1 = self.p1
  597.         p2 = self.p2
  598.         return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)
  599.  
  600.    
  601. class Rectangle(_BBox):
  602.    
  603.     def __init__(self, p1, p2):
  604.         _BBox.__init__(self, p1, p2)
  605.  
  606.     def __repr__(self):
  607.         return "Rectangle({}, {})".format(str(self.p1), str(self.p2))
  608.    
  609.     def _draw(self, canvas, options):
  610.         p1 = self.p1
  611.         p2 = self.p2
  612.         x1,y1 = canvas.toScreen(p1.x,p1.y)
  613.         x2,y2 = canvas.toScreen(p2.x,p2.y)
  614.         return canvas.create_rectangle(x1,y1,x2,y2,options)
  615.        
  616.     def clone(self):
  617.         other = Rectangle(self.p1, self.p2)
  618.         other.config = self.config.copy()
  619.         return other
  620.  
  621.  
  622. class Oval(_BBox):
  623.    
  624.     def __init__(self, p1, p2):
  625.         _BBox.__init__(self, p1, p2)
  626.  
  627.     def __repr__(self):
  628.         return "Oval({}, {})".format(str(self.p1), str(self.p2))
  629.  
  630.        
  631.     def clone(self):
  632.         other = Oval(self.p1, self.p2)
  633.         other.config = self.config.copy()
  634.         return other
  635.    
  636.     def _draw(self, canvas, options):
  637.         p1 = self.p1
  638.         p2 = self.p2
  639.         x1,y1 = canvas.toScreen(p1.x,p1.y)
  640.         x2,y2 = canvas.toScreen(p2.x,p2.y)
  641.         return canvas.create_oval(x1,y1,x2,y2,options)
  642.    
  643. class Circle(Oval):
  644.    
  645.     def __init__(self, center, radius):
  646.         p1 = Point(center.x-radius, center.y-radius)
  647.         p2 = Point(center.x+radius, center.y+radius)
  648.         Oval.__init__(self, p1, p2)
  649.         self.radius = radius
  650.  
  651.     def __repr__(self):
  652.         return "Circle({}, {})".format(str(self.getCenter()), str(self.radius))
  653.        
  654.     def clone(self):
  655.         other = Circle(self.getCenter(), self.radius)
  656.         other.config = self.config.copy()
  657.         return other
  658.        
  659.     def getRadius(self):
  660.         return self.radius
  661.  
  662.                  
  663. class Line(_BBox):
  664.    
  665.     def __init__(self, p1, p2):
  666.         _BBox.__init__(self, p1, p2, ["arrow","fill","width"])
  667.         self.setFill(DEFAULT_CONFIG['outline'])
  668.         self.setOutline = self.setFill
  669.  
  670.     def __repr__(self):
  671.         return "Line({}, {})".format(str(self.p1), str(self.p2))
  672.  
  673.     def clone(self):
  674.         other = Line(self.p1, self.p2)
  675.         other.config = self.config.copy()
  676.         return other
  677.  
  678.     def _draw(self, canvas, options):
  679.         p1 = self.p1
  680.         p2 = self.p2
  681.         x1,y1 = canvas.toScreen(p1.x,p1.y)
  682.         x2,y2 = canvas.toScreen(p2.x,p2.y)
  683.         return canvas.create_line(x1,y1,x2,y2,options)
  684.        
  685.     def setArrow(self, option):
  686.         if not option in ["first","last","both","none"]:
  687.             raise GraphicsError(BAD_OPTION)
  688.         self._reconfig("arrow", option)
  689.        
  690.  
  691. class Polygon(GraphicsObject):
  692.    
  693.     def __init__(self, *points):
  694.         # if points passed as a list, extract it
  695.         if len(points) == 1 and type(points[0]) == type([]):
  696.             points = points[0]
  697.         self.points = list(map(Point.clone, points))
  698.         GraphicsObject.__init__(self, ["outline", "width", "fill"])
  699.  
  700.     def __repr__(self):
  701.         return "Polygon"+str(tuple(p for p in self.points))
  702.        
  703.     def clone(self):
  704.         other = Polygon(*self.points)
  705.         other.config = self.config.copy()
  706.         return other
  707.  
  708.     def getPoints(self):
  709.         return list(map(Point.clone, self.points))
  710.  
  711.     def _move(self, dx, dy):
  712.         for p in self.points:
  713.             p.move(dx,dy)
  714.    
  715.     def _draw(self, canvas, options):
  716.         args = [canvas]
  717.         for p in self.points:
  718.             x,y = canvas.toScreen(p.x,p.y)
  719.             args.append(x)
  720.             args.append(y)
  721.         args.append(options)
  722.         return GraphWin.create_polygon(*args)
  723.  
  724. class Text(GraphicsObject):
  725.    
  726.     def __init__(self, p, text):
  727.         GraphicsObject.__init__(self, ["justify","fill","text","font"])
  728.         self.setText(text)
  729.         self.anchor = p.clone()
  730.         self.setFill(DEFAULT_CONFIG['outline'])
  731.         self.setOutline = self.setFill
  732.  
  733.     def __repr__(self):
  734.         return "Text({}, '{}')".format(self.anchor, self.getText())
  735.    
  736.     def _draw(self, canvas, options):
  737.         p = self.anchor
  738.         x,y = canvas.toScreen(p.x,p.y)
  739.         return canvas.create_text(x,y,options)
  740.        
  741.     def _move(self, dx, dy):
  742.         self.anchor.move(dx,dy)
  743.        
  744.     def clone(self):
  745.         other = Text(self.anchor, self.config['text'])
  746.         other.config = self.config.copy()
  747.         return other
  748.  
  749.     def setText(self,text):
  750.         self._reconfig("text", text)
  751.        
  752.     def getText(self):
  753.         return self.config["text"]
  754.            
  755.     def getAnchor(self):
  756.         return self.anchor.clone()
  757.  
  758.     def setFace(self, face):
  759.         if face in ['helvetica','arial','courier','times roman']:
  760.             f,s,b = self.config['font']
  761.             self._reconfig("font",(face,s,b))
  762.         else:
  763.             raise GraphicsError(BAD_OPTION)
  764.  
  765.     def setSize(self, size):
  766.         if 5 <= size <= 36:
  767.             f,s,b = self.config['font']
  768.             self._reconfig("font", (f,size,b))
  769.         else:
  770.             raise GraphicsError(BAD_OPTION)
  771.  
  772.     def setStyle(self, style):
  773.         if style in ['bold','normal','italic', 'bold italic']:
  774.             f,s,b = self.config['font']
  775.             self._reconfig("font", (f,s,style))
  776.         else:
  777.             raise GraphicsError(BAD_OPTION)
  778.  
  779.     def setTextColor(self, color):
  780.         self.setFill(color)
  781.  
  782.  
  783. class Entry(GraphicsObject):
  784.  
  785.     def __init__(self, p, width):
  786.         GraphicsObject.__init__(self, [])
  787.         self.anchor = p.clone()
  788.         #print self.anchor
  789.         self.width = width
  790.         self.text = tk.StringVar(_root)
  791.         self.text.set("")
  792.         self.fill = "gray"
  793.         self.color = "black"
  794.         self.font = DEFAULT_CONFIG['font']
  795.         self.entry = None
  796.  
  797.     def __repr__(self):
  798.         return "Entry({}, {})".format(self.anchor, self.width)
  799.  
  800.     def _draw(self, canvas, options):
  801.         p = self.anchor
  802.         x,y = canvas.toScreen(p.x,p.y)
  803.         frm = tk.Frame(canvas.master)
  804.         self.entry = tk.Entry(frm,
  805.                               width=self.width,
  806.                               textvariable=self.text,
  807.                               bg = self.fill,
  808.                               fg = self.color,
  809.                               font=self.font)
  810.         self.entry.pack()
  811.         #self.setFill(self.fill)
  812.         self.entry.focus_set()
  813.         return canvas.create_window(x,y,window=frm)
  814.  
  815.     def getText(self):
  816.         return self.text.get()
  817.  
  818.     def _move(self, dx, dy):
  819.         self.anchor.move(dx,dy)
  820.  
  821.     def getAnchor(self):
  822.         return self.anchor.clone()
  823.  
  824.     def clone(self):
  825.         other = Entry(self.anchor, self.width)
  826.         other.config = self.config.copy()
  827.         other.text = tk.StringVar()
  828.         other.text.set(self.text.get())
  829.         other.fill = self.fill
  830.         return other
  831.  
  832.     def setText(self, t):
  833.         self.text.set(t)
  834.  
  835.            
  836.     def setFill(self, color):
  837.         self.fill = color
  838.         if self.entry:
  839.             self.entry.config(bg=color)
  840.  
  841.            
  842.     def _setFontComponent(self, which, value):
  843.         font = list(self.font)
  844.         font[which] = value
  845.         self.font = tuple(font)
  846.         if self.entry:
  847.             self.entry.config(font=self.font)
  848.  
  849.  
  850.     def setFace(self, face):
  851.         if face in ['helvetica','arial','courier','times roman']:
  852.             self._setFontComponent(0, face)
  853.         else:
  854.             raise GraphicsError(BAD_OPTION)
  855.  
  856.     def setSize(self, size):
  857.         if 5 <= size <= 36:
  858.             self._setFontComponent(1,size)
  859.         else:
  860.             raise GraphicsError(BAD_OPTION)
  861.  
  862.     def setStyle(self, style):
  863.         if style in ['bold','normal','italic', 'bold italic']:
  864.             self._setFontComponent(2,style)
  865.         else:
  866.             raise GraphicsError(BAD_OPTION)
  867.  
  868.     def setTextColor(self, color):
  869.         self.color=color
  870.         if self.entry:
  871.             self.entry.config(fg=color)
  872.  
  873.  
  874. class Image(GraphicsObject):
  875.  
  876.     idCount = 0
  877.     imageCache = {} # tk photoimages go here to avoid GC while drawn
  878.    
  879.     def __init__(self, p, *pixmap):
  880.         GraphicsObject.__init__(self, [])
  881.         self.anchor = p.clone()
  882.         self.imageId = Image.idCount
  883.         Image.idCount = Image.idCount + 1
  884.         if len(pixmap) == 1: # file name provided
  885.             self.img = tk.PhotoImage(file=pixmap[0], master=_root)
  886.         else: # width and height provided
  887.             width, height = pixmap
  888.             self.img = tk.PhotoImage(master=_root, width=width, height=height)
  889.  
  890.     def __repr__(self):
  891.         return "Image({}, {}, {})".format(self.anchor, self.getWidth(), self.getHeight())
  892.                
  893.     def _draw(self, canvas, options):
  894.         p = self.anchor
  895.         x,y = canvas.toScreen(p.x,p.y)
  896.         self.imageCache[self.imageId] = self.img # save a reference  
  897.         return canvas.create_image(x,y,image=self.img)
  898.    
  899.     def _move(self, dx, dy):
  900.         self.anchor.move(dx,dy)
  901.        
  902.     def undraw(self):
  903.         try:
  904.             del self.imageCache[self.imageId]  # allow gc of tk photoimage
  905.         except KeyError:
  906.             pass
  907.         GraphicsObject.undraw(self)
  908.  
  909.     def getAnchor(self):
  910.         return self.anchor.clone()
  911.        
  912.     def clone(self):
  913.         other = Image(Point(0,0), 0, 0)
  914.         other.img = self.img.copy()
  915.         other.anchor = self.anchor.clone()
  916.         other.config = self.config.copy()
  917.         return other
  918.  
  919.     def getWidth(self):
  920.         """Returns the width of the image in pixels"""
  921.         return self.img.width()
  922.  
  923.     def getHeight(self):
  924.         """Returns the height of the image in pixels"""
  925.         return self.img.height()
  926.  
  927.     def getPixel(self, x, y):
  928.         """Returns a list [r,g,b] with the RGB color values for pixel (x,y)
  929.        r,g,b are in range(256)
  930.  
  931.        """
  932.        
  933.         value = self.img.get(x,y)
  934.         if type(value) ==  type(0):
  935.             return [value, value, value]
  936.         elif type(value) == type((0,0,0)):
  937.             return list(value)
  938.         else:
  939.             return list(map(int, value.split()))
  940.  
  941.     def setPixel(self, x, y, color):
  942.         """Sets pixel (x,y) to the given color
  943.        
  944.        """
  945.         self.img.put("{" + color +"}", (x, y))
  946.        
  947.  
  948.     def save(self, filename):
  949.         """Saves the pixmap image to filename.
  950.        The format for the save image is determined from the filname extension.
  951.  
  952.        """
  953.        
  954.         path, name = os.path.split(filename)
  955.         ext = name.split(".")[-1]
  956.         self.img.write( filename, format=ext)
  957.  
  958.        
  959. def color_rgb(r,g,b):
  960.     """r,g,b are intensities of red, green, and blue in range(256)
  961.    Returns color specifier string for the resulting color"""
  962.     return "#%02x%02x%02x" % (r,g,b)
  963.  
  964. def test():
  965.     win = GraphWin()
  966.     win.setCoords(0,0,10,10)
  967.     t = Text(Point(5,5), "Centered Text")
  968.     t.draw(win)
  969.     p = Polygon(Point(1,1), Point(5,3), Point(2,7))
  970.     p.draw(win)
  971.     e = Entry(Point(5,6), 10)
  972.     e.draw(win)
  973.     win.getMouse()
  974.     p.setFill("red")
  975.     p.setOutline("blue")
  976.     p.setWidth(2)
  977.     s = ""
  978.     for pt in p.getPoints():
  979.         s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
  980.     t.setText(e.getText())
  981.     e.setFill("green")
  982.     e.setText("Spam!")
  983.     e.move(2,0)
  984.     win.getMouse()
  985.     p.move(2,3)
  986.     s = ""
  987.     for pt in p.getPoints():
  988.         s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
  989.     t.setText(s)
  990.     win.getMouse()
  991.     p.undraw()
  992.     e.undraw()
  993.     t.setStyle("bold")
  994.     win.getMouse()
  995.     t.setStyle("normal")
  996.     win.getMouse()
  997.     t.setStyle("italic")
  998.     win.getMouse()
  999.     t.setStyle("bold italic")
  1000.     win.getMouse()
  1001.     t.setSize(14)
  1002.     win.getMouse()
  1003.     t.setFace("arial")
  1004.     t.setSize(20)
  1005.     win.getMouse()
  1006.     win.close()
  1007.  
  1008. #MacOS fix 2
  1009. #tk.Toplevel(_root).destroy()
  1010.  
  1011. # MacOS fix 1
  1012. update()
  1013.  
  1014. if __name__ == "__main__":
  1015.     test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement