9/3/18

Drawing SVG paths in Python (expanding svg beyond web design) for PyGame, Tkinter, & Turtle

I HAVED MOVED THIS ARTICLE TO MY NEW BLOG HERE

Python has always had a rich GUI and graphics options. Some of them built-in such as Tkinter and Turtle Graphics, and also other modules like PyGame, PyOpenGL, Matplotlib.

The Web which started off with fairly primitive graphics ability with animated gifs, images, and java applets, but now has dynamic JavaScript, CSS, and especially Scaled Vector Graphics (SVG).

SVG Paths are particularly great for defining curving paths that combine lines, ellipses, cubic and quadratic Biezer curves.

I will show you a package for python that will allow you to draw paths in PyGame, TKinter, and with Turtle Graphics:

The all use the svg.path package that can be installed with pip install svg.path or pip3 install svg.path. (See svg.path · PyPI )

This library allows you to draw paths with lines, cubic and quadratic beizer curves, and ellipses. It will create a path by a series of method calls, or by using a path string as specified for the SVG d attribute for CSS: (see Mozilla SVG curves tutorial)

Quadratic Path:
Cubic Path:
Ellipse (Arc) Path:
To use the svg.path package for drawing d attribute path strings:

from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, parse_path
d = "M100,200 C100,100 250,100 250,200 S400,300 400,200"
p = parse_path(d)

The code above would define a path object named x that would represent the path defined by the string in d. This path defines a move to 100,200 and then two cubic curves:

Red Curve Shows Path
Now that we have a path object:

x

we can call the point method to get a x,y position on the path expressed as a python complex number for a percent distance along the path expressed as a fraction from 0.0 to 1.0.

p x.point(0.5)

would return the point half way along path: (250+200j)

p2 = (p.real, p.imag) would convert the complex number to a tuple (250, 200) representing the x and y values referenced by p2.

Now complete code to render path to PyGame Window (associated video):

 

Now code for tkinter window:


Now code for turtle graphics window (note in turtle graphics curve is flipped vertically since the y axis is positive in the upper direction:



HAVE FUN!
-- Professor Gerry Jenkins

5 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. thank you. You are a great teacher

    ReplyDelete
  4. Hi Gerry. How would I save a bezier to a sag file without Tinker , PyGame etc. Just a basic svg file Thank regards

    ReplyDelete
  5. Sorry should read SVG file lol!

    ReplyDelete

Please comment or give suggestions for follow up articles