Presentation is loading. Please wait.

Presentation is loading. Please wait.

Graphics Taken from notes by Dr. Neil Moore & Dr. Debby Keen

Similar presentations


Presentation on theme: "Graphics Taken from notes by Dr. Neil Moore & Dr. Debby Keen"— Presentation transcript:

1 Graphics Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CS 115 Lecture 10 Graphics Taken from notes by Dr. Neil Moore & Dr. Debby Keen

2 The graphics library So far all our programs have interacted with the user through standard input and output (keyboard and shell window) Plain-text input (input) and output (print) Can we do something that looks nicer?

3 Why GUI in Python Most students are visual learners.
Approximately 65% of the population are visual learner It motivates beginners (students) to learn programming language. (Students hate/bored/don’t fully understand programs using shell). It helps students understand the basic elements of the programming (iterations, selections, functions, lists, files). Incorporate graphics into the class’s assignment and labs.

4 Graphics Libraries in Python
Use the turtle library (for more details click here). Use the graphics library designed by Dr. John N Zelle. (for more details click here) Use Pygame Library (for more details click here). Use Tkinter. GUI frameworks (or toolkits) (for more details click here). Others (for 3D graphics use PyOpenGL and piglet, for Visual Python, use vpython, Others. ) We will use the graphics library designed by Dr. John N Zelle in my intro to programming course for the following reasons. Simple. Fit introductory programming courses level.

5 Steps Need for Using Graphics Library
First: Download the graphics library (graphics.py) from here. Second: Save the library inside: Windows: c:\Python34\Lib\site-packages Mac::/Library/Frameworks/Python.framework/Versions/3. 4/lib/python3.4/site-packages Others: you can also save the library inside the same folder where you have the source code file. Third: Review the following reference module for any help.

6 Classes, objects and constructors
Object oriented programming: classes, objects and methods A class is a type (kind of thing that can be stored in a variable) Especially a user- or library-defined type In Python, str, float, int, etc. are also classes. An object is a particular thing of that type. So int is a class, and 42 is an object of that class. str is a class and “abracadabra” is an object. Point is a class, Point(100, 100) is an object.

7 Classes, objects and constructors
Why did we have to write it as Point(100, 100)? Unlike Python’s built-in types (3, 4.5, ‘abc’), most classes don’t have literals – symbols that stand for an object. Instead, you call a constructor to make a new object. A special function that returns a new object The name of the constructor is the same as the name of the class.

8 Classes in the graphics library
The Zelle graphics library defines several classes. Among them: GraphWin – a window for drawing graphics Point – an (x, y) coordinate Line – a line segment with two endpoints Circle – a circle with a center point and radius Rectangle – a rectangle (given by two opposite corners) Oval – an oval that fits inside a “bounding box” Polygon – defined by connecting a sequence of Points. Text – text with a given string value, position, size, etc. Entry – box for user to enter input, has position, size, etc. Image – object that holds a GIF file, has position, size, etc. The complete reference page:

9 Getting started Begin by importing the library:
import graphics Or: from graphics import * Now we need to create a window to draw in. The class for windows is called GraphWin Constructor: graphics.GraphWin (title, width, height) Or just graphics.GraphWin() (default values: “Graphics Window”, 200 x 200) Call the constructor, and save the new object in a variable (an assignment statement) We’ll need it later. window = graphics.GraphWin(“115 Program”, 600, 400)

10 Getting started The window usually closes when the program exits.
Keep it open by waiting for a mouse click: win.getMouse() More about getMouse later Close on exit doesn’t always work in the IDE Or when the program crashes Can eat up lots of system resources and eventually need a reboot! Be safe by always calling win.close()at the end!

11 Drawing graphics objects
Let’s make a line going from the upper left to lower right of the graphics window. To do that, we use the Line class. Constructor: graphics.Line(point1, point2) What’s a “point”? Another class! Constructor: graphics.Point(x, y) (x and y are floats) By default, (0, 0) is the upper left corner of graphics window Upside-down compared to Cartesian plan in math!

12 Drawing graphics objects
You can use a constructor as an argument, so from graphics import Line, Point diagonal = Line(Point(0,0), Point(600, 400)) Making the line does not actually draw it! One more step: tell it to draw itself in the window diagonal.draw(window) Why? Programs can have multiple windows open! Or you might want to set the line’s color first.

13 Methods What’s going on with the diagonal.draw(window)?
draw is a method of the Line class A method is like a function that works on an object “Something the object can do” In OOP, methods are how the program interacts with objects Syntax: obj.method(arguments) obj is an object (usually a variable) method is the name of the method

14 Methods Semantics: calls the function named “method” in obj’s class, sending it obj as the object to work on Methods can return values just like ordinary functions x = point.getX() The draw method does not return anything (like the function print) It’s a stand-alone statement. diagonal.draw(win)

15 More shapes: circles The Circle class represents a circle (surprise!)
What information is needed to draw a circle? The Center: that’s a Point. The Radius: that’s a number (distance from center to edge). eye = Circle (Point(250, 250), 200) its center is at (250, 250) Its radius is 200, top is at (y = 50), bottom at (y = 450) As with Line, we have to draw the circle to display it: eye.draw(win)

16 Rectangles We could draw a rectangle already, using four Lines.
But there is an easier way which we will see also has another benefit shortly What information do we need to draw a rectangle? Four corners? We really only need two opposite corners The graphics library can figure out the other two points.

17 Rectangles What is its width? 250 – 50 = 200 Height? 350 – 100 = 250
box = Rectangle (Point(50,100), Point(250, 350)) What is its width? 250 – 50 = 200 Height? 350 – 100 = 250 We gave the upper-left and lower-right corners but you don’t have to do those specifically. Just make sure you give two opposite corners. box = Rectangle (Point(250, 100), Point(50, 350))

18 Polygons We can also make a general polygon shape:
Any number of sides, at any angle How could we specify all that? List the vertices (corners) tri = Polygon(Point(100, 100), Point (300, 100), Point (200, 250)) tri would be a triangle (has 3 corners) You can have any number of points. Draws a line from the first point to the second Then from the second to the third Finally, from the last point back to the first Order matters! If you have more than 3 points, anyway.

19 Ovals An oval is a stretched-out “squashed” circle.
How would we specify an oval? Several possibilities: center and two radii, two foci, … The graphics library uses a bounding box. Class Oval The constructor takes two Point arguments The corners of a rectangle (the bounding box) The oval will fit in the box as tightly as possible. Does not actually draw the bounding box! ov = Oval (Point(100, 200), Point(400, 300)) ov.draw(win)

20 Images The graphics library can draw images
It supports GIF format files, not JPEG! You give the position where you want the center of the image, and a filename pic = Image(Point(250, 250), “pic.gif”) The image will be centered at (250, 250) The GIF file should be in the same folder location as your py file. Whoever runs your program needs the image file too. As usual, use pic.draw(win) to display the image.

21 More methods for graphics objects
You’ve seen all the constructors now And how to draw them Let’s look at some more things you can do with the objects once we have them (some more methods) obj.setWidth(pixels) Changes the width of the shape’s lines obj.move(dx, dy) Moves the shape by dx in the x direction, by dy in the y direction (can be positive or negative or zero) The numbers are added to the original coordinates Can do this even after the shape is drawn – so animation!

22 More methods for graphics objects
obj.undraw() Erases the shape immediately Anything “behind” becomes visible again Be careful not to UNdraw something that has not been DRAWN yet! Gives a Run-time error!

23 Color methods Shapes have two different colors associated with them: the fill and the outline The fill color is used for inside the shape box.setFill(“blue”) You specify the color name as a string Points and Lines don’t have an “inside” This is why Rectangle and Polygon are better than just a bunch of Lines – they have “insides”! The outline color is used for the border line1.setOutline(“red”) For a Line or a Point, that’s the entire shape The window as a whole (GraphWin) has a background color. win.setBackground(“yellow”)

24 Color methods The color names are a bit obscure (“firebrick”? “purple4”?) Or you can specify Red Green Blue values line1.setOutline (color_rgb(255, 128, 0)) # orange Go to this link if you need more details:

25 Drawing Text You can display text in the graphics window
You need the location (Point) where you want the center of the string, and a string greeting = Text(Point(250, 250), “Hello”) You can specify the font size greeting.setSize(30) # between 5 and 36 You can also make it bold and/or italic greeting.setStyle(“bold”) greeting.setStyle(“italic”) The library supports a few typefaces: greeting.setFace(“courier”) greeting.setFace(“times roman”)

26 Outputting numeric values
Suppose you had a variable like width which has an integer value. You want to put it on the graphics window. myresult = Text(Point(150, 100), width)#bad But this is NOT good. It is only a number, no label! It is easier to make ONE string which is used by ONE Text object. myresult = Text(Point(150, 100), “the width is “ + str(width)) # better! Typecast the numeric variable to a string then concatenate it with the label (including spaces as needed). This makes one string which is then displayed with the Text object.

27 Interacting with the user
What if a graphics program needs input from the user? You could use the input function call, but that uses the keyboard and Shell window Making the user switch back and forth is annoying … and it doesn’t work well in WingIDE! We can make a graphical text-entry box input_box = Entry(center, width) center is a Point object (where the box will be centered) width is a number of characters (not pixels) This controls the size of the input box, not the size of the input. The user can enter more characters (it scrolls)

28 Interacting with the user
You can set the initial text, font size, color… input_box.setText(“default”) Very useful to give default value that user can get by just clicking on the screen without any typing input_box.setSize(24) # 24 point input_box.setTextColor(“green”) After you have the object the way you want, don’t forget to draw it! input_box.draw(win)

29 Getting user input from an Entry object
After you’ve drawn the Entry object, you MUST give the user time to actually type in the box Use win.getMouse() Then you use the getText() method to actually get what the user typed user_input = input_box.getText() Returns a string just like the input function Use a typecast if you need a number type temperature = float(in_box.getText())


Download ppt "Graphics Taken from notes by Dr. Neil Moore & Dr. Debby Keen"

Similar presentations


Ads by Google