圣誕節就要到了,是不是有一種想要畫一顆漂亮的圣誕樹的沖動呢?Python 可以輕松實現這個愿望!接下來,我們就來一起學習如何用 Python 畫出一顆漂亮的圣誕樹。
import turtle # 畫圓 def circle(size): turtle.speed(100) turtle.pencolor("#E60000") turtle.fillcolor("#E60000") turtle.begin_fill() turtle.circle(size) turtle.end_fill() # 畫星星 def star(size): turtle.speed(100) turtle.pencolor("gold") turtle.fillcolor("gold") turtle.begin_fill() for i in range(5): turtle.forward(size) turtle.right(144) turtle.forward(size) turtle.left(72) turtle.end_fill() # 畫圣誕樹 def christmas_tree(height): turtle.speed(100) # 畫樹干 turtle.pencolor("brown") turtle.fillcolor("brown") turtle.penup() turtle.setposition(0, 0) turtle.pendown() turtle.begin_fill() turtle.goto(20, 0) turtle.goto(20, -height) turtle.goto(-20, -height) turtle.goto(-20, 0) turtle.end_fill() # 畫樹葉 turtle.pencolor("green") turtle.fillcolor("green") turtle.penup() turtle.goto(-100, -height) turtle.pendown() turtle.begin_fill() turtle.goto(0, height/2) turtle.goto(100, -height) turtle.goto(0, -height/2) turtle.goto(-100, -height) turtle.end_fill() # 畫圓 turtle.penup() turtle.goto(0, height/2) turtle.pendown() circle(height/10) turtle.penup() turtle.goto(10, height/2) turtle.pendown() circle(height/10) turtle.penup() turtle.goto(-10, height/2) turtle.pendown() circle(height/10) # 畫星星 turtle.penup() turtle.goto(0, height/2+height/10*0.8) turtle.pendown() star(height/10) # 主函數 if __name__ == "__main__": turtle.setup(500, 500) turtle.penup() turtle.goto(0, -200) turtle.pendown() christmas_tree(200) turtle.exitonclick()
上述代碼中,我們定義了三個函數,分別用于畫圓、畫星星和畫圣誕樹。在主函數中,我們通過 turtle 庫,控制海龜來畫出一顆漂亮的圣誕樹。
如果你想要更加個性化的圣誕樹,不妨修改代碼中的顏色、尺寸等參數。希望大家在這個圣誕節里,畫出屬于自己的漂亮圣誕樹!