Python 作为一种高级编程语言已经在编程领域中占有了举足轻重的地位。在计算机视觉和图形学领域中,Python 也有着不可替代的地位。利用 Python 的第三方库 turtle 绘制图形时,使画笔颜色随机变换会使图形更加生动有趣。
import turtleimport random# 颜色列表colors = ["red", "orange", "yellow", "green", "blue", "purple"]# 迭代绘制图形def draw(number):for i in range(number):# 随机选择颜色color = random.choice(colors)turtle.pencolor(color)# 随机选择角度和边长angle = random.randint(1, 360)length = random.randint(10, 100)# 绘制图形turtle.forward(length)turtle.right(angle)# 初始化画笔和窗口turtle.speed(0)turtle.pensize(3)turtle.bgcolor("black")# 迭代绘制多个图形for i in range(20):draw(10)turtle.right(18)# 点击窗口退出程序turtle.exitonclick()
在上面的代码中,我们首先定义了一个颜色列表,里面存放了六种颜色,随后定义了一个绘制图形的函数 draw。绘制函数中通过调用 random.choice 函数从颜色列表中随机选择颜色,并使用 turtle.pencolor 函数设置画笔颜色。接着,在 for 循环中,我们通过随机选择角度和边长来绘制图形,每次循环都随机变换颜色,使图形更加绚丽多彩。
最后,我们通过调用 turtle.exitonclick() 函数实现了在单击窗口后退出程序的功能,方便再次运行程序。