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

A line with a curved bend

The most interesting lines are curved. Change the straight, two-segment line of the previous example into a smooth curve that fits parallel to the ends of each segment. Tkinter makes the curve out of 12 straight segments. 12 segments is the default number. However, you can change it to any other sensible number.

How to do it...

Substitute the line canvas_1.create_line(x1,y1, x2,y2, x3,y3) with the line canvas_1.create_line(x1,y1, x2,y2, x3,y3, smooth="true").

The line is now curved. This is immensely useful when making drawings – we only need to specify a minimal number of points and Tkinter fits a curved shape to it.

How it works...

The program output for smooth="true" attribute is shown in the next screenshot. The smooth='true' attribute hides a large amount of serious mathematical curve manufacture taking place under the hood.

To fit a curve to a pair of intersecting lines requires the curve and the lines to run parallel at the beginning and end but in the middle an entirely different process known as spline fitting is used. The consequence of this is that this kind of curvaceous smoothing is computationally expensive and if you do too much of it your program execution slows down. This has implications for what kinds of action can be successfully animated.

How it works...

There's more...

What we do later is to use the curve attribute to make more pleasing and exciting shapes. Ultimately you could accumulate for yourself a library of shapes. If you did this you would be re-creating some vector graphics that are freely available from the web. Look at www.openclipart.org. The pictures which are freely downloadable from this site are in SVG (Scaled Vector Graphics) format. If you look at the code of these pictures in a text editor you will see lines of code that are vaguely similar to the way these Tkinter programs specify the points. Some techniques for extracting useful shapes from existing SVG pictures will be demonstrated in Chapter 6, Working with Pictures.