turtle_spirograph.py

# =========================================================
# Spirograph using the turtle module
# =========================================================

# ---------------------------------------------------------
# --- import
# ---------------------------------------------------------

import math
import sys
import turtle as t 

if sys.version_info.major is 3:
    from tkinter import *
    py3 = True
else:
    from Tkinter import *
    py3 = False

# ---------------------------------------------------------
# --- global (default) variables
# ---------------------------------------------------------

R = 160         # raidus of large circle
r =  20         # raidus of small circle
d =  60         # distance from drawing point to
                # center of small circle

# ---------------------------------------------------------
# --- functions
# ---------------------------------------------------------

# --- calculate x,y coordinates of the drawing point
# --- return x,y as integers

def xyCoords(a,R,r,d):
    rad = math.radians(a)
    x = ((R-r)*math.cos(rad)) + \
            (d*math.cos(((R-r)/r)*rad))
    y = ((R-r)*math.sin(rad)) + \
            (d*math.sin(((R-r)/r)*rad))
    return (int(x),int(y))

def quit():
    ##print('Key Input Event')
    sys.exit()

# ---------------------------------------------------------
# --- main
# ---------------------------------------------------------

# --- don't show the turtle icon

t.hideturtle()

# --- ask the user for input

R = t.numinput('Large Circle','Raidus',R)
r = t.numinput('Small Circle','Raidus',r)
d = t.numinput('Drawing Point','Distance',d)

# --- quit?

t.listen(None,None)
t.onkeypress(quit,key='q')

# --- move to the starting point

startx,starty = xyCoords(0,R,r,d)
t.penup()
t.goto(startx,starty)
t.pendown()

# --- keep drawing until the starting point is reached

a = 0

while True:
    a += 1
    x,y = xyCoords(a,R,r,d)
    t.goto(x,y)
    ##print('Coords: a={}  x={}, y={}'.format(a,x,y))
    if startx == x and starty == y:
        break

# --- main loop

mainloop()