温馨提示×

怎么用python画圣诞树

小亿
87
2024-02-27 17:25:14
栏目: 编程语言

使用Python绘制圣诞树可以使用turtle库来实现,下面是一个简单的绘制圣诞树的示例代码:

import turtle

def draw_triangle(x, y, size, color):
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    turtle.fillcolor(color)
    turtle.begin_fill()
    for _ in range(3):
        turtle.forward(size)
        turtle.right(120)
    turtle.end_fill()

def draw_tree(x, y, size):
    draw_triangle(x, y, size, "green")
    draw_triangle(x - size/2, y + size, size, "green")
    draw_triangle(x + size/2, y + size, size, "green")
    draw_triangle(x - size, y + size*2, size, "green")
    draw_triangle(x + size, y + size*2, size, "green")
    draw_triangle(x - size*1.5, y + size*3, size, "green")
    draw_triangle(x + size*1.5, y + size*3, size, "green")
    draw_triangle(x - size*2, y + size*4, size, "green")
    draw_triangle(x + size*2, y + size*4, size, "green")

def draw_star(x, y, size):
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    turtle.fillcolor("yellow")
    turtle.begin_fill()
    for _ in range(5):
        turtle.forward(size)
        turtle.right(144)
    turtle.end_fill()

def main():
    turtle.speed(0)
    turtle.bgcolor("black")
    draw_tree(0, -200, 50)
    draw_star(0, 100, 20)
    turtle.hideturtle()
    turtle.done()

if __name__ == "__main__":
    main()

运行该代码后,将会在窗口中显示一个简单的圣诞树。您可以根据需要调整树的大小和位置。

0