Python 2.6 Graphics Cookbook
上QQ阅读APP看书,第一时间看更新

A two segment line with a sharp bend

Lines do not have to be straight. A more general type of line can be made up of many straight segments joined together. You simply decide where you want the points that join sections of the multi-segment line and the order in which they should be joined.

How to do it...

The instructions are the same as for recipe 1. Just use the name sharp_bend.py when you write, save, and execute this program.

Just make a list of the x,y pairs defining each point and place them in the sequence that you want them connected in. The list can be as long as you like.

#sharp_bend.py
#>>>>>>>>>>>
from Tkinter import *
root = Tk()
root.title('Sharp bend')
cw = 300                                      # canvas width
ch = 200                                      # canvas height
canvas_1 = Canvas(root, width=cw, height=ch, background="white")
canvas_1.grid(row=0, column=1)

x1 = 50
y1 = 10
x2 = 20
y2 = 80
x3 = 150
y3 = 60

canvas_1.create_line(x1,y1,  x2,y2,  x3,y3)
root.mainloop()

How it works...

For clarity only three points have been defined: first =(x1,y1), second =(x2,y2) and third = (x3, y3). However, there is no limit to the number of sequential points that could be specified.

How it works...

The preceding screenshot shows the line with a sharp bend.

There's more...

Ultimately you could have complicated figures stored as long sequences of points in files on some storage device. For example, you might want to produce something like a cartoon strip.

You could construct a library of body parts and face features seen from different angles. There could be a selection of different mouth and eye shapes. The daily chore of assembling your comic strip could be partially automated. One of the things you would need to think about would be how to scale the component parts to be larger or smaller and also how to position them in different places and even rotate them to different angles. All these ideas are developed in this book.

In particular see the next examples of how complex shapes can be stored and manipulated in a relatively compact form. The SVG (Scaled Vector Graphics) standard for drawing manipulation, particularly on web pages, uses a similar but different convention for representing shapes. Because both SVG and Tkinter are well defined it means that you can construct code for converting from one form to the other.

Examples of this are shown in Chapter 6, Working with Pictures.