python中画同心圆环
时间: 2023-11-14 10:11:34 浏览: 41
在Python中,可以使用turtle库来绘制同心圆环。下面是一个绘制同心圆环的示例代码:
```
import turtle
import random
turtle.screensize(600, 600, "white")
turtle.speed(0)
turtle.hideturtle()
def getRandomColor():
''' 产生随机颜色 '''
r = random.randint(16, 255)
g = random.randint(16, 255)
b = random.randint(16, 255)
return "#" + str(hex(r)).replace("0x", "") + str(hex(g)).replace("0x", "") + str(hex(b)).replace("0x", "")
def drawCircle():
''' 绘制同心圆环 '''
step = 12 # 圆环半径增长的步长
for i in range(1, 256, step):
color = getRandomColor() # 获得随机颜色
turtle.goto(0, -i) # 注意移动起笔位置
turtle.color(color,color) # 设置颜色
turtle.pensize(step * 1.5) # 为了不留下空白,将线宽设置为1.5倍步长
turtle.pendown() # 落笔
turtle.circle(i, 360) # 绘制圆弧
turtle.penup() # 抬笔
if __name__ == "__main__":
drawCircle()
turtle.done()
```
该代码使用turtle库绘制同心圆环,其中getRandomColor()函数用于产生随机颜色,drawCircle()函数用于绘制同心圆环。在drawCircle()函数中,使用for循环控制圆环半径的增长,使用goto()函数移动起笔位置,使用color()函数设置颜色,使用pensize()函数设置线宽,使用pendown()函数落笔,使用circle()函数绘制圆弧,使用penup()函数抬笔。最后,使用turtle.done()函数显示绘制结果。