Lab 7: Creating graphics from data files

Now that we can build up a data file and read it in to a Python program, let’s build another picture using a data file!

What to Draw

For this project, I want you to construct a robot. To give you an idea what such a critter might look like, here is an example:

../../_images/SImpleRobot.png

Your robot does not need to look exactly like this, just something similar will do.

Obviously, you need to draw a few different shapes, each with different colore to get this robot on the screen.

Note

You can see all the colors supported by the graphics package we are using at this link: Tk Color Names.

Creating a data file

Your first job is to set up a text file containing the data we need to draw a simple picture (not a complex one, but you can if you like!) Use the example code from today’s lecture to get started.

Your data file will be one string or number per line, and you use the first string to call a function that will draw the object. That function will read in the additional numbers needed, then draw the object.

Here is a sample program to draw a circle:

from graphics import *

win = GraphWin("Circles", 300,500)

def drawCircle(x,y,radius,color):
    c = Circle(Point(x,y),radius)
    c.setFill(color)
    c.draw(win)

def main():
    fin = open("circles.dat","r")
    code = fin.readline().strip()
    while code != '':
        if code == "circle":
            color = fin.readline().strip()
            x = int(fin.readline())
            y = int(fin.readline())
            radius = int(fin.readline())
            drawCircle(x,y,radius,color)
        code = fin.readline().strip()

main()
win.getMouse()
win.close()

Here is the data file I used:

circle
blue
60
60
50
circle
yellow
90
90
25

And, here is what it produced:

../../_images/circles.png

That should get you going!

What to turn in

You will need to place two files in a folder named lab9

  • drawing.py

  • drawing.dat