+ All Categories
Home > Documents > Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects &...

Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects &...

Date post: 12-Mar-2021
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
69
Richard E Sarkis CSC 161: The Art of Programming Lecture Objects & Graphics
Transcript
Page 1: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Richard E Sarkis CSC 161: The Art of Programming

Lecture

Objects & Graphics

Page 2: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Class Administrivia

Page 3: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Agenda

• To understand the concept of objects and how they can be used to simplify programs

• To be familiar with the various objects available in the graphics library

• To be able to create objects in programs and call appropriate methods to perform graphical computations

Page 4: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Overview

• Each data type can represent a certain set of values, and each had a set of associated operations

• The traditional programming view is that data is passive – it’s manipulated and combined with active operations

Page 5: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Overview

• Modern computer programs are built using an object-oriented approach

• Most applications you’re familiar with have Graphical User Interfaces (GUI) that provide windows, icons, buttons and menus

• There’s a graphics library (graphics.py) written by John Zelle. It’s based on Tkinter

Page 6: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Objects of Objects

Page 7: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Objects 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.

Page 8: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Objects of Objects

• Data inside an object is called a data attribute

• Continue to think of them as variables

• Functions and procedures inside the object are called methods

• They are still functions or procedures, just in a different context

Page 9: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Objects of Objects

• Suppose we want to develop a data processing system for a college or university.

• We must keep records on students who attend the school. Each student will be represented as an object.

Page 10: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Objects of Objects

• The student object would contain data like:

• Name

• ID number

• Courses taken

• Campus Address

• Home Address

• GPA

• Etc.

Page 11: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Objects of Objects

• The student object should also respond to requests.

• We may want to send out a campus-wide mailing, so we’d need a campus address for each student.

• We could send the printCampusAddress to each student object. When the student object receives the message, it prints its own address.

Page 12: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Objects of Objects

• Objects may refer to other objects.

• Each course might be represented by an object:

• Instructor

• Student roster

• Prerequisite courses

• When and where the class meets

Page 13: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Objects of Objects

• Sample Operation

• addStudent()

• delStudent()

• changeRoom()

• Etc.

Page 14: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Namespaces

Page 15: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Namespaces

• Everything in Python is an object, which can be…

• Variables storing values like 1, 3.14, or "foo"

• Defined functions, like print(), main(), etc.

• Defined classes*

• Imported modules

• Objects can be given the same name, causing a conflict! Modules avoid name conflicts!

Page 16: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Namespaces

• A namespace is a grouping of symbols (such as variables, functions, classes)

• A module is regarded as a unified structure of things that semantically belong together.

• They allow you to avoid naming conflicts when you use different modules that may use similar names

Page 17: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Namespaces

• For example, lets say you have two different Python modules (lets call them ModuleA and ModuleB) written by different people, which both contain a function called "func". Without namespaces, importing both modules would create a conflict between the two functions, and you wouldn't be able to use them both. However, with namespaces, you can access the two different functions through ModuleA.func(...) and ModuleB.func(...).

Page 18: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Namespaces

• When you go to a family dinner, "Bob" obviously refers to your nephew. At the coffee shop, it is your favorite barista, at work, it is ambiguous, because there are two Bobs, and at the gym, it is meaningless, because there are no Bobs there. If you want to refer to those Bob outside of those situations, you have to provide some context, nephew Bob, coffee Bob, bald Bob from work.

Page 19: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

>>> import math>>> x = 33>>> y = 11.2>>> my_str = “Foobar”>>> dir()

['math', 'my_str', 'x', 'y']

y

math

xmy_str

…sin()sqrt()

lower()“Foobar” …join()

pi

Page 20: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

Page 21: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

• The graphics.py library supplied with the supplemental materials.

• Two location choices:

• In Python’s Lib directory with other libraries

• In the same folder as your graphics program

Page 22: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

• Since this is a library, we need to import the graphics commands

>>> import graphics

• A graphics window is a place on the screen where the graphics will appear.

>>> win = graphics.GraphWin()

• This command creates a new window titled “Graphics Window.”

Page 23: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

• GraphWin is an object assigned to the variable win. We can manipulate the window object through this variable

• Windows can be closed/destroyed by issuing the command win.close()

Page 24: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

• It’s tedious to use the graphics.<name> notation to access the graphics library routines.

• from graphics import *

• The “from” statement allows you to load specific functions from a library module. “*” will load all the functions, or you can list specific ones.

Page 25: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

• Caveat! Remember "wildcard" (*) imports are not good form

• It pollutes your namespaces, and can cause naming collisions

Page 26: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

• Doing the import this way eliminates the need to preface graphics commands with graphics.<name>

>>> from graphics import GraphWin>>> win = GraphWin()

Page 27: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

• Let's say you plan on drawing circles, polygons in addition to displaying a window

• Selectively import what you need!

>>> from graphics import GraphWin, Circle, Polygon>>> win = GraphWin()

Page 28: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

• A graphics window is a collection of points called pixels (picture elements).

• The default GraphWin is 200 pixels tall by 200 pixels wide (40,000 pixels total).

• One way to get pictures into the window is one pixel at a time, which would be tedious. The graphics routine has a number of predefined routines to draw geometric shapes.

Page 29: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

• The simplest object is the Point. Like points in geometry, point locations are represented with a coordinate system (x, y), where x is the horizontal location of the point and y is the vertical location.

• The origin (0,0) in a graphics window is the upper left corner.

• X values increase from left to right, y values from top to bottom.

• Lower right corner is (199, 199)

Page 30: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

>>> from graphics import Point, GraphWin>>> p = Point(50, 60)>>> p.getX()50>>> p.getY()60>>> win = GraphWin()>>> p.draw(win)>>> p2 = Point(140, 100)>>> p2.draw(win)

Page 31: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Simple Graphics Programming

>>> ### Open a graphics window>>> win = GraphWin('Shapes')>>> ### Draw a red circle centered at point >>> ### (100, 100) with radius 30>>> center = Point(100, 100)>>> circ = Circle(center, 30)>>> circ.setFill('red')>>> circ.draw(win)>>> ### Put a textual label in the center of the circle>>> label = Text(center, "Red Circle")>>> label.draw(win)>>> ### Draw a square using a Rectangle object>>> rect = Rectangle(Point(30, 30), Point(70, 70))>>> rect.draw(win)>>> ### Draw a line segment using a Line object>>> line = Line(Point(20, 30), Point(180, 165))>>> line.draw(win)>>> ### Draw an oval using the Oval object>>> oval = Oval(Point(20, 150), Point(180, 199))>>> oval.draw(win)

Page 32: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

Page 33: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

• Computation is preformed by asking an object to carry out one of its operations

• In the previous example we manipulated GraphWin, Point, Circle, Oval, Line, Text and Rectangle

• These are examples of classes

Page 34: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

• To create a new instance of a class, we use a special operation called a constructor

<class-name>(<param1>, <param2>, …)

• <class-name> is the name of the class we want to create a new instance of, e.g. Circle or Point

• The parameters are required to initialize the object. For example, Point requires two numeric values

Page 35: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

• p = Point(50, 60) The constructor for the Point class requires two parameters, the x and y coordinates for the point

• These values are stored as instance variables inside of the object

Page 36: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

Only the most relevant instance variables are “public” (others include the color, window they belong to, etc.)

72 Chapter 4. Objects and Graphics

x:

60

50

p:

y:

Point

Figure 4.4: Conceptual picture of the result of p = Point(50,60). The variable p refers to a freshlycreated Point having the given coordinates.

<object>.<method-name>(<param1>, <param2>, ...)

The number and type of the parameters is determined by the method being used. Some meth-ods require no parameters at all. You can find numerous examples of method invocation in theinteractive examples above.

As examples of parameterless methods, consider these two expressions:

p.getX()

p.getY()

The getX and getY methods return the x and y values of a point, respectively. Methods such asthese are sometimes called accessors, because they allow us to access information from the instancevariables of the object.

Other methods change the values of an object’s instance variables, hence changing the state ofthe object. All of the graphical objects have a move method. Here is a specification:

move(dx, dy): Moves the object dx units in the x direction and dy units in the y direction.

To move the point p to the right 10 units, we could use this statement.

p.move(10,0)

This changes the x instance variable of p by adding 10 units. If the point is currently drawn ina GraphWin, move will also take care of erasing the old image and drawing it in its new position.Methods that change the state of an object are sometimes called mutators.

The move method must be supplied with two simple numeric parameters indicating the distanceto move the object along each dimension. Some methods require parameters that are themselvescomplex objects. For example, drawing a Circle into a GraphWin involves two objects. Let’sexamine a sequence of commands that does this.

circ = Circle(Point(100,100), 30)

win = GraphWin()

circ.draw(win)

Page 37: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

• To perform an operation on an object, we send the object a message. The set of messages an object responds to are called the methods of the object.

• Methods are like functions that live inside the object.

• Methods are invoked using dot-notation: <object>.<method-name>(<param1>, <param2>, …)

Page 38: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

• p.getX() and p.getY() returns the x and y values of the point. Routines like these are referred to as accessors because they allow us to access information from the instance variables of the object.

Page 39: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

• Other methods change the state of the object by changing the values of the object’s instance variables.

• p.move(dx, dy) moves the object dx units in the x-direction and dy in the y-direction.

• Move erases the old image and draws it in its new position. Methods that change the state of an object are called mutators.

Page 40: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

>>> circ = Circle(Point(100, 100), 30) >>> win = GraphWin() >>> circ.draw(win)

• The first line creates a circle with radius 30 centered at (100,100).

• We used the Point constructor to create a location for the center of the circle.

• The last line is a request to the Circle object circ to draw itself into the GraphWin object win.

Page 41: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

The draw method uses information about the center and radius of the circle from the instance variable.

4.4. Using Graphical Objects 73

The first line creates a Circle with a center located at the Point (100, 100) and a radius of 30.Notice that we used the Point constructor to create a location for the first parameter to the Circle

constructor. The second line creates a GraphWin. Do you see what is happening in the third line?This is a request for the Circle object circ to draw itself into the GraphWin object win. The visibleeffect of this statement is a circle in the GraphWin centered at (100, 100) and having a radius of 30.Behind the scenes, a lot more is happening.

Remember, the draw method lives inside the circ object. Using information about the centerand radius of the circle from the instance variables, the draw method issues an appropriate sequenceof low-level drawing commands (a sequence of method invocations) to the GraphWin. A conceptualpicture of the interactions among the Point, Circle and GraphWin objects is shown in Figure 4.5.Fortunately, we don’t usually have to worry about these kinds of details; they’re all taken care ofby the graphical objects. We just create objects, call the appropriate methods, and let them do thework. That’s the power of object-oriented programming.

Circle

y:

x:

100

100

Pointcenter:

radius:

draw( )...

GraphWin

.

.

.

Low-level drawing commands

win:

30

circ:

Figure 4.5: Object interactions to draw a circle.

There is one subtle “gotcha” that you need to keep in mind when using objects. It is possiblefor two different variables to refer to exactly the same object; changes made to the object throughone variable will also be visible to the other. Suppose we are trying to write a sequence of codethat draws a smiley face. We want to create two eyes that are 20 units apart. Here is a sequence ofcode intended to draw the eyes.

## Incorrect way to create two circles.

leftEye = Circle(Point(80, 50), 5)

leftEye.setFill(’yellow’)

leftEye.setOutline(’red’)

Page 42: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

• It’s possible for two different variables to refer to the same object – changes made to the object through one variable will be visible to the other.

>>> left_eye = Circle(Point(80,50), 5) >>> left_eye.setFill('yellow') >>> left_eye.setOutline('red') >>> right_eye = left_eye >>> right_eye.move(20,0)

• The idea is to create the left eye and copy that to the right eye which gets moved 20 units.

Page 43: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

• The assignment right_eye = left_eye makes right_eye and left_eye refer to the same circle!

• The situation where two variables refer to the same object is called aliasing

Page 44: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

74 Chapter 4. Objects and Graphics

rightEye = leftEye

rightEye.move(20,0)

The basic idea is to create the left eye and then copy that into a right eye which is then moved over20 units.

This doesn’t work. The problem here is that only one Circle object is created. The assignment

rightEye = leftEye

simply makes rightEye refer to the very same circle as leftEye. Figure 4.6 shows the situation.When the Circle is moved in the last line of code, both rightEye and leftEye refer to it in itsnew location on the right side. This situation where two variables refer to the same object is calledaliasing, and it can sometimes produce rather unexpected results.

rightEye:

leftEye: Circle

y:

x:

50

80

Pointcenter:

radius: 10

Figure 4.6: Variables leftEye and rightEye are aliases.

One solution to this problem would be to create a separate circle for each eye.

## A correct way to create two circles.

leftEye = Circle(Point(80, 50), 5)

leftEye.setFill(’yellow’)

leftEye.setOutline(’red’)

rightEye = Circle(Point(100, 50), 5)

rightEye.setFill(’yellow’)

rightEye.setOutline(’red’)

This will certainly work, but it’s cumbersome. We had to write duplicated code for the two eyes.That’s easy to do using a “cut and paste” approach, but it’s not very elegant. If we decide to changethe appearance of the eyes, we will have to be sure to make the changes in two places.

The graphics library provides a better solution; all graphical objects support a clone methodthat makes a copy of the object. Using clone, we can rescue the original approach.

## Correct way to create two circles, using clone.

leftEye = Circle(Point(80, 50), 5)

leftEye.setFill(’yellow’)

leftEye.setOutline(’red’)

Page 45: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

• There are two ways to get around this.

• We could make two separate circles, one for each eye:

>>> left_eye = Circle(Point(80, 50), 5) >>> left_eye.setFill('yellow') >>> left_eye.setOutline('red') >>> right_eye = Circle(Point(100, 50), 5) >>> right_eye.setFill('yellow') >>> right_eye.setOutline('red')

Page 46: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

• The graphics library has a better solution. Graphical objects have a clone method that will make a copy of the object!

>>> # Correct way to create two >>> # circles, using clone >>> left_eye = Circle(Point(80, 50), 5) >>> left_eye.setFill('yellow') >>> left_eye.setOutline('red') >>> right_eye = left_eye.clone() >>> # right_eye is an exact copy of the left >>> right_eye.move(20, 0)

Page 47: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

Page 48: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

Page 49: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Using Graphical Objects

78 Chapter 4. Objects and Graphics

Now we just need to figure out where the opposite (upper right) corner of the bar should beso that we can draw an appropriate rectangle. In the vertical direction, the height of the bar isdetermined by the value of principal. In drawing the scale, we determined that 100 pixels isequal to $5,000. This means that we have 100/5000 = 0.02 pixels to the dollar. This tells us,for example, that a principal of $2,000 should produce a bar of height 2000(.02) = 40 pixels. Ingeneral, the y position of the upper-right corner will be given by 230−(principal)(0.02). (Rememberthat 230 is the 0 point, and the y coordinates decrease going up).

How wide should the bar be? The window is 320 pixels wide, but 40 pixels are eaten up by thelabels on the left. That leaves us with 280 pixels for 11 bars: 280/11 = 25.4545. Let’s just makeeach bar 25 pixels; that will give us a bit of margin on the right side. So, the right edge of our firstbar will be at position 40 + 25 = 65.

We can now fill in the details for drawing the first bar into our algorithm.

Draw a rectangle from (40, 230) to (65, 230 - principal * 0.02)

At this point, we have made all the major decisions and calculations required to finish out theproblem. All that remains is to percolate these details into the rest of the algorithm. Figure 4.8shows the general layout of the window with some of the dimensions we have chosen.

0.0K

2.5K

5.0K

7.5K

10.0K

(40,230)

320

(0,0)

(319,239)25

10

40

50(315,230)

240

Figure 4.8: Position of elements in future value bar graph.

Let’s figure out where the lower-left corner of each bar is going to be located. We chose a barwidth of 25, so the bar for each successive year will start 25 pixels farther right than the previousyear. We can use a variable year to represent the year number and calculate the x coordinate ofthe lower left corner as (year)(25) + 40. (The +40 leaves space on the left edge for the labels.) Ofcourse, the y coordinate of this point is still 230 (the bottom of the graph).

To find the upper-right corner of a bar, we add 25 (the width of the bar) to the x value of thelower-left corner. The y value of the upper right corner is determined from the (updated) value ofprincipal exactly as we determined it for the first bar. Here is the refined algorithm:

Page 50: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Interactive Graphics

Page 51: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Interactive Graphics

• 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

• Event-driven programming draws interface elements (widgets) on the screen and then waits for the user to do something

Page 52: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Interactive Graphics

• An event is generated whenever a user moves the mouse, clicks the mouse, or types a key on the keyboard

• An event is an object that encapsulates information about what just happened!

• The event object is sent to the appropriate part of the program to be processed, for example, a button event

Page 53: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Interactive Graphics

• The graphics module hides the underlying, low-level window management and provides two simple ways to get user input in a GraphWin

Page 54: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Mouse Clicks

Page 55: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Mouse Clicks

• We can get graphical information from the user via the getMouse method of the GraphWin class

• When getMouse is invoked on a GraphWin, the program pauses and waits for the user to click the mouse somewhere in the window

• The spot where the user clicked is returned as a Point

Page 56: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Mouse Clicks

• The following code reports the coordinates of a mouse click: from graphics import GraphWin win = GraphWin("Click Me!") p = win.getMouse() print("You clicked", p.getX(), p.getY())

• We can use the accessors like getX and getY or other methods on the point returned.

Page 57: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Mouse Clicksfrom graphics import GraphWin, Polygon, Text, Point

def main(): win = GraphWin("Draw a Triangle") message = Text(Point(100, 190), "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) 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() win.close()

Page 58: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Mouse Clicks

Page 59: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Mouse Clicks

• Notes:

• If you are programming in a windows environment, using the .pyw extension on your file will cause the Python shell window to not display when you double-click the program icon.

• There is no triangle class. Rather, we use the general polygon class, which takes any number of points and connects them into a closed shape.

Page 60: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Mouse Clicks

• Once you have three points, creating a triangle polygon is easy: triangle = Polygon(p1, p2, p3)

• A single text object is created and drawn near the beginning of the program. message = Text(Point(5,0.5), "Click on three points") message.draw(win)

• To change the prompt, just change the text to be displayed. message.setText("Click anywhere to

Page 61: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Handling Textual Input

Page 62: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Handling Textual Input

• The triangle program’s input was done completely through mouse clicks. There’s also an Entry object that can get keyboard input.

• The Entry object draws a box on the screen that can contain text. It understands setText and getText, with one difference that the input can be edited.

Page 63: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Handling Textual Inputfrom graphics import GraphWin, Text, Rectangle, Entry, Point

def main(): win = GraphWin("Celsius Converter", 300, 200) # Draw the interface Text(Point(100, 50), "Celsius Temperature: ").draw(win) Text(Point(100,150), "Fahrenheit Temperature:").draw(win) _input = Entry(Point(200, 50), 5) _input.setText("0.0") _input.draw(win) output = Text(Point(200, 150),"") output.draw(win) button = Text(Point(150, 100),"Convert It") button.draw(win) Rectangle(Point(100, 125), Point(200,75)).draw(win) # wait for a mouse click win.getMouse()

# convert input celsius = float(_input.getText()) fahrenheit = 9.0/5.0 * celsius + 32

# display output and change button output.setText(fahrenheit) button.setText("Quit")

# wait for click and then quit win.getMouse() win.close()

Page 64: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Handling Textual Input

Page 65: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Handling Textual Input

Page 66: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Handling Textual Input

• When run, this program produces a window with an entry box for typing in the Celsius temperature and a button to “do” the conversion.

• The button is for show only! We are just waiting for a mouse click anywhere in the window.

Page 67: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Handling Textual Input

• Initially, the input entry box is set to contain “0.0”.

• The user can delete this value and type in another value.

• The program pauses until the user clicks the mouse – we don’t care where so we don’t store the point!

Page 68: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Handling Textual Input

• The input is processed in three steps:

• The value entered is converted into a number with float.

• This number is converted to degrees Fahrenheit.

• This number is then converted to a string and formatted for display in the output text area.

Page 69: Objects & Graphics - University of Rochesterrsarkis/csc161/_static/lectures/Objects & Graphics.pdfUsing Graphical Objects • To create a new instance of a class, we use a special

Questions?


Recommended