Exercises for Lesson 7

Back to Lesson 7

Fun aside: this file will let you visualize all of the named colors you can use with Tkinter.

Exercise 1: Creating and using graphical objects

For each of the following code snippets, think about what attributes the graphics object has, and then run the code and see what gets displayed.

from graphics import *

# (a)

win = GraphWin("Exercise 1a: Point")

p = Point(130, 130)
p.draw(win)

win.getMouse()
win.close()

# (b)

win = GraphWin("Exercise 1b: Circle")

circ = Circle(Point(30,40), 25)
circ.setFill("blue")
circ.setOutline("red")
circ.draw(win)

win.getMouse()
win.close()

# (c)

win = GraphWin("Exercise 1c: Rectangle")

rect = Rectangle(Point(20,20), Point(40,40))
rect.setFill("DarkOliveGreen4")
rect.setWidth(3)
rect.draw(win)

win.getMouse()
win.close()

# (d)

win = GraphWin("Exercise 1d: Line")

line = Line(Point(100,100), Point(100,200))
line.setOutline("dark violet")
line.setArrow("first")
line.draw(win)

win.getMouse()
win.close()

# (e)

win = GraphWin("Exercise 1e: Oval")

oval = Oval(Point(50, 50), Point(60, 100))
oval.draw(win)

win.getMouse()
win.close()

# (f)

win = GraphWin("Exercise 1f: Polygon")

shape = Polygon(Point(50,50), Point(100,100),
                Point(50,100), Point(100,50))
shape.setFill("orange")
shape.draw(win)

win.getMouse()
win.close()

# (g)

win = GraphWin("Exercise 1g: Text")

text = Text(Point(100,100), "Hello, world!")
text.setFace("courier")
text.setSize(16)
text.setStyle("italic")
text.draw(win)

win.getMouse()
win.close()

Back to Lesson 7

Exercise 2: Interactive graphics

Imagine you want to draw a triangle based on where a user clicks. The following code will get you most of the way there. How would you fill in the two # TODO to do this?

from graphics import *

def main():
    # Set up the window
    winWidth, winHeight = 800, 600
    win = GraphWin("Draw a triangle", winWidth, winHeight)
    win.setBackground("white")

    # Print a welcome message to the user
    message = Text(Point(winWidth / 2, winHeight - winHeight * 0.1),
                   "Click on three points to make a triangle")
    message.draw(win)

    # Get and draw three vertices of a triangle
    # TODO

    # Somehow draw the triangle
    triangle = # TODO
    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()

main()

Back to Lesson 7