Exercise 15.4. Swampy (see Case study: interface design) provides a module named World, which defines a user-defined type also called World. You can import it like this:
from swampy.World import World
Or, depending on how you installed Swampy, like this:
from World import World
The following code creates a World object and calls themainloopmethod, which waits for the user.
world = World()world.mainloop()
A window should appear with a title bar and an empty square. We will use this window to drawPoints, Rectangles and other shapes. Add the following lines before calling mainloopand run theprogram again.
canvas = world.ca(width=500, height=500, background='white')bbox = [[-150,-100], [150, 100]]canvas.rectangle(bbox, outline='black', width=2, fill='green4')
You should see a green rectangle with a black outline. The first line creates a Canvas, which appearsin the window as a white square. The Canvas object provides methods like rectanglefor drawingvarious shapes.
bboxis a list of lists that represents the “bounding box” of the rectangle. The first pair of coordinatesis the lower-left corner of the rectangle; the second pair is the upper-right corner.
You can draw a circle like this:
canvas.circle([-25,0], 70, outline=None, fill='red')
The first parameter is the coordinate pair for the center of the circle; the second parameter is the radius.
If you add this line to the program, the result should resemble the national flag of Bangladesh (seehttp: // en. wikipedia. org/ wiki/ Gallery_ of_ sovereign-state_ flags).
- Write a function called draw_rectanglethat takes a Canvas and a Rectangle as argumentsand draws a representation of the Rectangle on the Canvas.
- Add an attribute named colorto your Rectangle objects and modify draw_rectanglesothat it uses the color attribute as the fill color.
- Write a function called draw_pointthat takes a Canvas and a Point as arguments and drawsa representation of the Point on the Canvas.
- Define a new class called Circle with appropriate attributes and instantiate a few Circle objects.Write a function called draw_circlethat draws circles on the canvas.
- Write a program that draws the national flag of the Czech Republic. Hint: you can draw apolygon like this:
points = [[-150,-100], [150, 100], [150, -100]]canvas.polygon(points, fill='blue')
I have written a small program that lists the available colors; you can download it from http:// thinkpython. com/ code/ color_ list. py.