返回
用 Python 画个生日蛋糕为朋友庆生
后端
2024-01-12 08:56:57
import turtle
import math
import random
# 创建一个画布
screen = turtle.Screen()
screen.setup(width=800, height=600)
screen.bgcolor("white")
# 创建一个海龟
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
t.pensize(2)
# 画蛋糕底座
t.penup()
t.setpos(-200, -100)
t.pendown()
t.color("brown")
t.begin_fill()
t.circle(200)
t.end_fill()
# 画蛋糕主体
t.penup()
t.setpos(-150, -50)
t.pendown()
t.color("pink")
t.begin_fill()
t.circle(150)
t.end_fill()
# 画蛋糕上的奶油
t.penup()
t.setpos(-100, 0)
t.pendown()
t.color("white")
t.begin_fill()
t.circle(100)
t.end_fill()
# 画蛋糕上的蜡烛
t.penup()
t.setpos(-50, 50)
t.pendown()
t.color("yellow")
t.begin_fill()
t.circle(20)
t.end_fill()
# 画蛋糕上的装饰
t.penup()
t.setpos(-75, 75)
t.pendown()
t.color("blue")
t.begin_fill()
t.circle(10)
t.end_fill()
t.penup()
t.setpos(0, 75)
t.pendown()
t.color("green")
t.begin_fill()
t.circle(10)
t.end_fill()
t.penup()
t.setpos(75, 75)
t.pendown()
t.color("red")
t.begin_fill()
t.circle(10)
t.end_fill()
# 写上生日祝福
t.penup()
t.setpos(-100, 125)
t.pendown()
t.color("black")
t.write("Happy Birthday!", font=("Arial", 20, "bold"))
# 隐藏海龟
t.hideturtle()
# 保存图片
screen.getcanvas().postscript(file="birthday_cake.eps")
# 退出画布
screen.exitonclick()
Python是一种用途广泛、简单易学的编程语言,它可以用来完成各种各样的任务,从数据分析到机器学习。turtle库是一个Python库,它可以用来创建和操作图形。在这个教程中,我们将使用turtle库来创建一个生日蛋糕的图形表示。
首先,我们需要导入turtle库。
import turtle
接下来,我们需要创建一个画布。画布是turtle库中用来创建图形的区域。
screen = turtle.Screen()
screen.setup(width=800, height=600)
screen.bgcolor("white")
现在,我们需要创建一个海龟。海龟是turtle库中用来在画布上绘制图形的对象。
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
t.pensize(2)
接下来,我们需要画蛋糕底座。蛋糕底座是一个圆形,我们将使用turtle库中的circle()方法来创建它。
t.penup()
t.setpos(-200, -100)
t.pendown()
t.color("brown")
t.begin_fill()
t.circle(200)
t.end_fill()
现在,我们需要画蛋糕主体。蛋糕主体也是一个圆形,我们将使用turtle库中的circle()方法来创建它。
t.penup()
t.setpos(-150, -50)
t.pendown()
t.color("pink")
t.begin_fill()
t.circle(150)
t.end_fill()
现在,我们需要画蛋糕上的奶油。蛋糕上的奶油也是一个圆形,我们将使用turtle库中的circle()方法来创建它。
t.penup()
t.setpos(-100, 0)
t.pendown()
t.color("white")
t.begin_fill()
t.circle(100)
t.end_fill()
现在,我们需要画蛋糕上的蜡烛。蛋糕上的蜡烛是一个圆柱体,我们将使用turtle库中的begin_fill()和end_fill()方法来创建它。
t.penup()
t.setpos(-50, 50)
t.pendown()
t.color("yellow")
t.begin_fill()
t.circle(20)
t.end_fill()
现在,我们需要画蛋糕上的装饰。蛋糕上的装饰是一个三角形,我们将使用turtle库中的begin_fill()和end_fill()方法来创建它。
t.penup()
t.setpos(-75, 75)
t.pendown()
t.color("blue")
t.begin_fill()
t.circle(10)
t.end_fill()
t.penup()
t.setpos(0, 75)
t.pendown()
t.color("green")
t.begin_fill()
t.circle(10)
t.end_fill()
t.penup()
t.setpos(75, 75)
t.pendown()
t.color("red")
t.begin_fill()
t.circle(10)
t.end_fill()
现在,我们需要写上生日祝福。我们将使用turtle库中的write()方法来写上生日祝福。
t.penup()
t.setpos(-100, 125)
t.pendown()
t.color("black")
t.write("Happy Birthday!", font=("Arial", 20, "bold"))
最后,我们需要隐藏海龟。
t.hideturtle()
现在,我们需要保存图片。
screen.getcanvas().postscript(file="birthday_cake.eps")
现在,我们需要退出画布。
screen.exitonclick()
现在,我们可以运行这个程序来创建一个生日蛋糕的图形表示。