Lecture Notes
Introduction to Programming and Algorithm Design (COP-1000)

Graphics with Python

These notes explain how to implement simple graphics and construct a Graphical User Interface (GUI) with Python. Python has a graphics library called Tkinter; John Zelle (Professor of Computer Science, Wartburg College, Waverly, Iowa), has written a simpler graphics library as a Python module called graphics, which we will use here.


Graphics Classes

  • Graphics classes are no different in concept from the classes we have been using
  • Objects instantiated from graphics classes
    • contain data (instance variables)
    • perform operations (methods)

  • To start with, we will use graphics objects instantiated from classes defined in the graphics library

Simple Graphics Programming

  • The graphics library has been written by John Zelle (Professor of Computer Science, Wartburg College, Waverly, Iowa); it is freely available
  • Save the graphics.py file in the directory in which you installed Python, in the Lib\site-packages folder
  • Note: to use this graphics module with IDLE, you need to make sure that IDLE was started without the "-n" (no subprocesses) switch; unfortunately, this switch is included by default in the shortcuts on the right-click menu when you install Python; you will either need to remove this switch (Folder options > File types) or start IDLE from the start menu
  • To use the library, first import it (either in the shell or a program file) with:
from graphics import *
  • The documentation of the classes and functions provided in a library is called an Application  Programming Interface or API; in the case of a graphics library, the client programmer will use the API to create GUIs
  • The API for the graphics.py module is available here (HTML) and here (PDF)
  • The basic graphics object is a GraphWin a moveable graphic window in which other graphics objects will be drawn
  • A GraphWin object is instantiated with this syntax:
windowName = GraphWin('title', x-size, y-size)

  • All three arguments are optional; the default size is 200 x 200 pixels
  • Each pixel has coordinates (x, y), where x is the number of horizontal pixels from the left of the window, and y is the number of vertical pixels from the top (not counting the title bar)
  • A GraphWin object has methods to "draw" a pixel at specified window coordinates (x, y), set a background color, wait for a mouse click and return the coordinates "clicked", and to close the window; see the graphics documentation for details

Using Graphical Objects Widgets

  • Various graphics objects can be instantiated and drawn in a GraphWin Point, Line, Circle, Rectangle, Oval, Polygon and Text objects (see API for detail)
  • Graphics objects are often called widgets
  • To draw a widget is a multi-step process:
    • instantiate the widget
    • set the widget's attributes (fill color, etc.) with its methods
    • draw the widget in a GraphWin, using its draw method
  • To instantiate a widget (like a Point, or Circle), we invoke its constructor  method, like instantiating any object:
object_ref = Class_name(parm_list)
  • For example, a Point widget can be instantiated like this:
p = Point(37, 123)
  • The Point widget p is instantiated, with its x and y coordinates saved as instance variables in the object; graphically:

  • Once an object has been instantiated, we can call on its methods to perform operations on it, using this syntax:

object_ref.method_name(parm_list)
  • Some classes provide methods that allow access to an object's instance variables   these methods are called accessors; for example, the Point class provides the getX and getY methods that return the object's x and y coordinates, respectively
  • Some classes provide methods that allow an object's instance variables to be modified these methods are called mutators; for example, the Point class includes the move method that modifies the object's x and y coordinates
  • For example, this sequence of statements in the shell will result in the window shown:
>>> from graphics import *
>>> myWin = GraphWin('Shapes')     
>>> p1 = Point(10,50)
>>> p1.draw(myWin)
>>> center = Point(100,100)
>>> cir = Circle(center,30)
>>> cir.setFill('red')
>>> cir.draw(myWin)
>>> l = Line(p1, center)
>>> l.setArrow('first')
>>> l.draw(myWin)
  • Remember that assigning one object reference to another creates an alias for the same object, not a copy; to duplicate a graphics object, use the clone method, which returns a copy of the object (or use the deepcopy method from the copy module):
>>> a = Circle(Point(100,100),20)
>>> b = a.clone()

Using Graphics to Enhance Output

  • Using just these basic shapes by themselves is not very productive, since they are not interactive they are only displayed; still, they can add a graphical dimension to a program's output
  • See sample program grades.py
    • Shows bar graph of three grades and mean
    • Takes some planning to design GraphWin and internal coordinate system; note how design is simplified with coordinate transformation
    • Complete program uses Line, Rectangle, and Text widgets
    • See sample program: throwRock.pyw
      • A GraphWin is instantiated with dimensions of 400 x 300
      • A "building" is drawn by calling the method drawBldg, and passing as an argument the GraphWin in which to draw a building and a stick figure to throw the rock
      • The nested loops display the path of the rock in 0.1 second intervals until it "hits the ground" (i.e., the y-coordinate of its center is > 300)
      • The sleep() function is the time library is used to pause execution for 0.1 seconds each time through the loop, to add realism to the display
      • Note: for you physics types, the horizontal velocity vx is constant (if we ignore air resistance), but the vertical velocity vy is increasing due to gravity; so the formulas for the distance traveled in each dimension (dx and dy) at time t are:

      dx = vxt
      dy =
      gt2  

      where g is the acceleration due to gravity (32 ft/sec/sec or 9.8 m/sec/sec)


Interactive Graphics

  • GUIs can be used for input as well as output, by providing them with interactive widgets like dialog boxes, buttons, and menus
  • The simplified Graphics API provides only two facilities for obtaining user input:
    • For mouse input, a GraphWin object's getMouse method waits for a mouse click in the window, and returns a Point object whose coordinates are the location of the mouse pointer
    • For text input, an Entry widget can be used to draw a box in a GraphWin in which the user can edit text, that can then be accessed with the Entry widget's getText method
  • Sample program: triangle.pyw
    • Demonstrates use of the getMouse method
  • Sample program: button2.py
    • Shows how to assemble a Button class from simpler widgets
  • Example (convert_gui.pyw): converts temperatures from the Celsius to Fahrenheit scales using a GUI. Features:
    • uses the setCoords method to establish a simpler coordinate system for the GraphWin from (0,0) in the lower left corner to (3,4) in the upper right of the window
    • draws the user interface using a combination of Text, Entry, and Rectangle widgets; the user will edit the text in the Entry object input, which is initially set to 0.0
    • uses the getMouse method to pause and wait for a mouse click; note that the mouse can be clicked anywhere in the window, not just in the box suggested
    • obtains the input with the getText method, converts it to a numeric value with the built-in eval() function, calculates the output and displays it
    • the text label in the "button" is changed to "Quit" and the getMouse method used to pause the program before the GraphWin close method ends the program
  • Example (throwRock2.pyw): improves on the above program to add an interactive interface to let the user specify the initial velocity
 Updated: 12.13.2010