python画图代码圣诞树
时间: 2023-09-26 10:11:47 浏览: 51
可以用以下 Python 代码来画圣诞树:
```python
# -*- coding: utf-8 -*-
# Python 3.x code to draw a Christmas Tree
from turtle import *
# Define function to draw and fill a rectangle.
def draw_rectangle(x, y, width, height, color):
fillcolor(color)
begin_fill()
setheading(0)
goto(x, y)
setheading(90)
forward(height)
setheading(180)
forward(width)
setheading(270)
forward(height)
setheading(0)
forward(width)
end_fill()
# Define function to draw and fill a circle.
def draw_circle(x, y, radius, color):
fillcolor(color)
begin_fill()
goto(x, y - radius)
setheading(0)
circle(radius)
end_fill()
# Define function to draw a triangle.
def draw_triangle(x, y, width, height, color):
fillcolor(color)
begin_fill()
goto(x, y)
setheading(0)
forward(width)
setheading(270)
forward(height)
setheading(230)
forward((width**2 + height**2)**0.5)
end_fill()
# Main function to draw the Christmas tree.
def draw_tree(x, y):
# Draw the trunk.
draw_rectangle(x - 20, y - 150, 40, 150, "brown")
# Define the height and width of each triangle layer.
layer_height = 40
layer_width = 150
# Define the number of triangle layers.
num_layers = 4
# Draw each layer of the tree (bottom-up).
for i in range(num_layers):
layer_color = "green" if i % 2 == 0 else "dark green"
layer_x = x - i * (layer_width / 2)
layer_y = y - 150 + i * layer_height
for j in range(i + 1):
draw_triangle(layer_x + j * layer_width, layer_y, layer_width, layer_height, layer_color)
# Draw the tree topper.
draw_rectangle(x - 30, y - 20, 60, 40, "yellow")
draw_triangle(x, y + 20, 50, 60, "yellow")
draw_circle(x, y + 60, 20, "yellow")
# Set up the turtle screen.
setup(600, 600)
title("Merry Christmas!")
bgcolor("skyblue")
# Draw the Christmas tree.
speed(0)
penup()
goto(0, -150)
pendown()
draw_tree(0, 0)
hideturtle()
# Keep the turtle screen open until manually closed.
done()
```
希望能回答您的问题,也希望您能享受圣诞节的快乐时光!