5. COMPUTING WITH GRAPHICS OBJECTS
Dennis Y. W. Liu and Rocky K. C. ChangOctober 8, 2015(Adapted from John Zelle’s slides)
Objectives• To construct a Graphical User Interface (GUI) window;• To construct various shapes, including dots, straight lines,
circles, rectangles, triangles and ovals;• To combine various shapes to construct complicated
graphics;• To understand the process of developing a graphical
interface;• To understand the coordinate system in a GUI window;• To construct a bar chart and a line graph;• To create interactive graphics using event-driven
programming.
The Object of Objects• Basic idea – view a complex system as the interaction of
simpler objects. An object is a sort of active data type that combines data and operations.
• Objects know stuff (contain data) and they can do stuff (have operations).
• Objects interact by sending each other messages.
Simple Graphics Programming• The utilization of objects in Python can be better
illustrated using Graphics programming.
EXERCISE 5.1Download the graphics.py library from http://mcsp.wartburg.edu/zelle/python/ and save it to the following path:C:\<pythron-home-directory>\Lib\site-packages
E.g., C:\Python34\Lib\site-packages
For MAC: Macintosh HD\Library\Frameworks\Python.framework\Versions\3.4\lib\python3.4\site-packages
EXERCISE 5.2Type the following code in the Shell: >>> import graphics>>> win = graphics.GraphWin()
Window Creation and Termination• This creates a window on the screen. • Here the variable “win” represents the window and soon
you will add other graphics on it.• To close the window, type>>> win.close()• We will be working with quite a few commands from the
graphics library. Python has an alternative form of import that can help out:
>>> from graphics import *>>> win = GraphWin()[Question] How to change the caption and the size of
the window?
EXERCISE 5.3Type the following code: >>> p = Point(50, 60)>>> win = GraphWin()>>> p.draw(win)
Drawing a Dot• By default, the window size created by the program is 200
x 200 pixels (height x width). • To locate a point (x, y) on the window, where x is the
horizontal position and y is the vertical position, we use (0, 0) to represent the upper-left corner of the window.• (199, 199) are the coordinates of lower-right corner of the window.
EXERCISE 5.4Type the following code: >>> p1 = Point(20, 30)>>> p2 = Point(180, 165)>>> line = Line(p1, p2)>>> line.draw(win)
Drawing a Line• To draw a line, you have specify the coordinates of two
ends of the line.• [Question] Can you draw a cross?
EXERCISE 5.5Type the following code: >>> center = Point(100, 100)>>> circ = Circle(center, 30)>>> circ.setFill(‘red’)>>> circ.draw(win)
Drawing a Circle• To draw a circle, we have to specify the center and the
radius (in pixel) of the circle.• [Question] How to draw a circle that is centered at
(20, 20) with a radius of 30 pixels?
EXERCISE 5.6Type the following code: >>> oval = Oval(Point(130, 240), Point(290, 330))>>> oval.draw(win)
Drawing an Oval• To draw an oval, we have to specify the two coordinates
of opposite corners of bounding box.
• [Question] How to construct an oval with a size 50 x 80 pixels centered in the window?
EXERCISE 5.7Type the following code: >>> win = GraphWin()>>> rect = Rectangle(Point(30, 50), Point(170, 160))>>> rect.draw(win)
Drawing a Rectangle• To construct a rectangle, we have to specify the two
coordinates of opposite corners.• [Question] How to construct a blue rectangle with a
size 38 x 49 pixels with (10, 20) as its top-left corner?
EXERCISE 5.8Type the following code: >>> win = GraphWin()>>> tri = Polygon(Point(30, 30), Point(70, 70), Point(90, 20))>>> tri.draw(win)
Drawing a Triangle• There is no triangle class. • There is a general class Polygon that can be used for any
multi-sided, close shape. • It accepts any number of points and creates a polygon by
using line segments to connect the points in the order given and to connect the last point back to the first.
• [Question] Create a trapezium of your desired size. Is there any relationship among the points?
EXERCISE 5.9Create a graphic window which looks like below. The window should have a dimension of 420 x 360.[Hint: objectname.setOutline(color)]
More complex graphics for data representation• Suppose we want to develop a program to determine the future
value of an investment. The formula is given by:
future value = principle * (1 + annual_interest_rate)year
• We invest $2000 at 15% interest for 5 years. • The following table shows the growth of the investment:
Years Value0 $2,000.001 $2,300.002 $2,645.003 $3,041.754 $3,498.015 $4,022.71
More complex graphics for data representation• We would like to display the information in a bar chart like
below:
More complex graphics for data representation• How can we achieve it?• Programming with graphics requires careful planning. You
will probably need a pencil and a piece of paper to draw some diagrams and scratch out calculations.• Step 1: Designing using Pseudocode• Step 2: Writing the Code
Step 1: Designing using Pseudocode• The following pseudocode illustrates the flow of logic of the
program:Create a GraphWinDraw scale labels on left side of windowDraw bar at position 0 with height corresponding to principalFor successive years 1 through 5
Calculate principal = principal * (1 + annual interest rate)Draw a bar for this year having a height corresponding to
principal
The Coordinates and Lengths
320
240
10
50
(0, 0)
(319, 239)45(50, 230)
Step 2: Writing the Code# futval_bar_chart.pyfrom graphics import * def main(): # Let us assume the principal and annual interest rate is fixed principal = 2000 apr = 0.15 # Create a graphics window with labels on left edge win = GraphWin("Investment Growth Chart", 320, 240) win.setBackground("white") Text(Point(20, 230), ' 0.0K').draw(win) Text(Point(20, 180), ' 1.0K').draw(win) Text(Point(20, 130), ' 2.0K').draw(win) Text(Point(20, 80), ' 3.0K').draw(win) Text(Point(20, 30), ' 4.0K').draw(win)
# Draw bar for initial principal barWidth = 45 height = principal * 0.05
Step 2: Writing the Code (con’t) bar = Rectangle(Point(50, 230), Point(50 + barWidth, 230 - height)) bar.setFill("green") bar.setWidth(2) bar.draw(win) # Draw bars for successive years for year in range(1, 6): # calculate value for the next year principal = principal * (1 + apr) # draw bar for this value xll = year * barWidth + 50 height = principal * 0.05 bar = Rectangle(Point(xll, 230), Point(xll + barWidth, 230 - height)) bar.setFill("green") bar.setWidth(2) bar.draw(win) input("Press <Enter> to quit") win.close() main()
EXERCISE 5.10Convert the bar chart above to a line chart as shown below:
Interactive Graphics• Graphical interface can be used as input as well. • In a GUI environment, users typically interact with their
applications by clicking on buttons, choosing items from menus, and typing information into on-screen text boxes.
• A technique called event-driven programming is adopted.• An interface element (also called control) is placed on the
window and waits for the user act on it (e.g., “click” on a button) to trigger an event. • An event will cause a series of code to be executed.
Drawing a Triangle• Write a program that allows the user to draw a triangle by
clicking on three points in a window.
Drawing a Triangle (con’t)# triangle.pyfrom graphics import * def main(): win = GraphWin("Draw a Triangle") win.setCoords(0.0, 0.0, 10.0, 10.0) message = Text(Point(5, 0.5), "Click on three points") message.draw(win) # Get and draw three vertices of triangle p1 = win.getMouse() p1.draw(win) p2 = win.getMouse() p2.draw(win)
Drawing a Triangle (con’t) p3 = win.getMouse() p3.draw(win) # Use Polygon object to draw the triangle triangle = Polygon(p1, p2, p3) triangle.setFill("peachpuff") triangle.setOutline("cyan") triangle.draw(win) # Wait for another click to exit message.setText("Click anywhere to quit.") win.getMouse() main()
EXERCISE 5.11Modify triangle.py. For each 3-click, the program should generate a triangle for the three points.
END
Top Related