- 用turtle模块创建图形
- 使用参数方程
- 利用数学方程生成曲线
- 用线段画曲线
- 用定时器来生成图形动画
- 将图形保存为图像文件
利用海龟画图绘制圆
import math
import turtle#Python的turtle模块来创建图案
#draw the circle using turtle
def drawCircleTurtle(x,y,r):
#move to the dtart of circle
turtle.up()#调用up告诉python提笔,即让笔离开虚拟的纸
turtle.setpos(x+r,y)#绘图前先定义海龟的位置
turtle.down()#调用down,开始绘图
#draw the circle
for i in range(0,365,5):#步长为5,变量i为角度参数
a = math.radians(i)#将角度转换为弧度
turtle.setpos(x+r*math.cos(a),y+r*math.sin(a))#绘制圆的参数方程
drawCircleTurtle(100,100,50)#调用圆形绘图函数
turtle.mainloop()#调用mainloop(),保持tkinter窗口打开

万花尺
- Spiro函数创造新turtle对象
- getParams()方法:初始化Spiro对象
- restart()方法:重置Spiro对象的绘制参数
- draw()方法:用连续的线段绘制曲线
- update()方法:利用线段绘制曲线创建动画
- SpiroAnimator类:同时绘制随机螺线
- genRandomParams()方法:生成随机参数
- restart()方法:重新启动程序
- update()方法:由定时器调用,以动画的形式更新所有的Spiro对象
- toggleTurtles()方法:显示或隐藏光标
- saceDrawing()方法:绘制保存PNG图像文件
import sys, random, argparse
import numpy as np
import math
import turtle
import random
from PIL import Image
from datetime import datetime
from fractions import gcd
#a class tat draws a Spirough
class Spiro:
#constructor
def __init__(self,xc,yc,col,R,r,l):
#creat the turtle object
self.t = turtle.Turtle()#创建一个新的turtle对象
#set the cursor shape
self.t.shape('turtle')#在光标的位置设置海龟
#set the step in degrees
self.step = 5#将参数绘图角度的增量设置为5
#setr the drawing cpmplete flag
self.drawingComplete = False#设置提个标志,在动画中使用它,它会产生一组螺线
#set the parameters
self.setparams(xc,yc,col,R,r,l)#调用设置函数
#initialize the drawing
self.restart()#调用设置函数
# set the parameters
def setparams(self, xc, yc, col, R, r, l) :
# the Spirograph parameters
self.xc = xc # 保存曲线中心坐标
self.yc = yc
self.R = int(R) # 将每个圆的半径转换为整数,并保留这些数值
self.r = int(r)
self.l = l
self.col = col
# reduce r/R to its smallest form by dividing with the GCO
gcdVal = gcd(self.r, self.R) # Python模块feacyion内置的gcd()方法来计算半径的GCD
self.nRot = self.r // gcdVal # 确定曲线的周期性
# get ratio of radii
self.K =