多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Python Turtle绘图:写春联(只写文字 / 画红纸优化)【难度2星】 ![](http://h.yiniuedu.com/6d9d5f8cc956e976abf3855a91aa364a) ``` # 案例2:写春联(画红纸优化)  现代方式(横批从左至右读,上联贴左) ### 程序初始化设置 import turtle # 导入turtle库(模块) turtle.bgcolor("#ffc3ff")  # 设置背景颜色为#ffc373,一种黄色。也可设置为深红色#661314 color_word="black" # 设置书法的颜色为black。如果背景颜色为深红色,建议书法文字用黄色#f4eb5e color_paper="#ea182a" # 设置红纸的颜色为#ea182a 横批="虎年大吉" # 定义字符串变量,存放横批的内容。变量名可以用汉字。 上联="沂牛教育开胜景" # 定义字符串变量,存放上联的内容 下联="高端托管展鸿图" # 定义字符串变量,存放下联的内容 # 变量x1和y1,控制上联第一个字的坐标位置 x1=-200 y1=80 # 变量x2和y2,控制下联第一个字的坐标位置 x2=200 y2=80 # 变量x3和y3,控制横批第一个字的坐标位置 x3=-70 y3=160 ### ① 写上联 # 画上联红纸 turtle.color(color_paper)  # 设置红纸的颜色 turtle.penup() turtle.goto(x1-30,y1+65) # 设置上联红纸的坐标 turtle.pendown() turtle.begin_fill() turtle.forward(60) turtle.right(90) turtle.forward(380) turtle.right(90) turtle.forward(60) turtle.right(90) turtle.forward(380) turtle.end_fill() # 写上联文字 turtle.color(color_word) # 设置春联文字的颜色为变量color_word for i in range(7) :        # 上联共有7个字,所以需要循环7次。 turtle.penup() turtle.goto(x1,y1) turtle.pendown() turtle.write(上联[i], align="center",font=("方正行楷简体",30,"bold")) y1=y1-50 ### ② 写下联 # 画下联红纸 turtle.setheading(0) turtle.color(color_paper)  # 设置红纸的颜色 turtle.penup() turtle.goto(x2-30,y2+65) # 设置下联红纸的坐标 turtle.pendown() turtle.begin_fill() turtle.forward(60) turtle.right(90) turtle.forward(380) turtle.right(90) turtle.forward(60) turtle.right(90) turtle.forward(380) turtle.end_fill() # 写下联文字 turtle.color(color_word) # 设置春联文字的颜色为变量color_word for i in range(7) :        # 下联共有7个字,所以需要循环7次。 turtle.penup() turtle.goto(x2,y2) turtle.pendown() turtle.write(下联[i], align="center",font=("方正行楷简体",30,"bold")) y2=y2-50 ### ③ 写横批 # 画横批红纸 turtle.color(color_paper)  # 设置红纸的颜色 turtle.setheading(0) # 让海龟的头部朝向右,即回到默认状态。 turtle.penup() turtle.goto(x3-35,y3+55) # 设置横批红纸的坐标 turtle.pendown() turtle.begin_fill() turtle.forward(210) turtle.right(90) turtle.forward(60) turtle.right(90) turtle.forward(210) turtle.right(90) turtle.forward(60) turtle.end_fill() # 写横批文字 turtle.color(color_word)    \# 设置春联文字的颜色为变量color_word for i in range(4) : # 横批共有4个字,所以需要循环4次。 turtle.penup() turtle.goto(x3,y3) turtle.pendown() turtle.write(横批[i], align="center",font=("方正行楷简体",30,"bold")) x3=x3+50 ### 海龟绘图结束,隐藏海龟 turtle.hideturtle() turtle.done() ```