飞道的博客

教你用Python画了一棵圣诞树

901人阅读  评论(0)

分享给大家一篇文章,教你怎样用Python画了一棵圣诞树,快来学习。

如何用Python画一个圣诞树呢?

最简单:


  
  1. height = 5
  2. ​
  3. stars = 1
  4. for i in range(height):
  5. print(( ' ' * (height - i)) + ( '*' * stars))
  6. stars += 2
  7. print(( ' ' * height) + '|')

效果:

哈哈哈哈,总有一种骗了大家的感觉。

其实本文是想介绍Turtle库来画圣诞树。


  
  1. import turtle
  2. ​
  3. screen = turtle.Screen()
  4. screen.setup( 375, 700)
  5. ​
  6. circle = turtle.Turtle()
  7. circle.shape( 'circle')
  8. circle.color( 'red')
  9. circle.speed( 'fastest')
  10. circle.up()
  11. ​
  12. square = turtle.Turtle()
  13. square.shape( 'square')
  14. square.color( 'green')
  15. square.speed( 'fastest')
  16. square.up()
  17. ​
  18. circle.goto( 0, 280)
  19. circle.stamp()
  20. ​
  21. k = 0
  22. for i in range( 1, 13):
  23. y = 30 * i
  24. for j in range(i - k):
  25. x = 30 * j
  26. square.goto(x, -y + 280)
  27. square.stamp()
  28. square.goto(-x, -y + 280)
  29. square.stamp()
  30. ​
  31. if i % 4 == 0:
  32. x = 30 * (j + 1)
  33. circle.color( 'red')
  34. circle.goto(-x, -y + 280)
  35. circle.stamp()
  36. circle.goto(x, -y + 280)
  37. circle.stamp()
  38. k += 3
  39. ​
  40. if i % 4 == 3:
  41. x = 30 * (j + 1)
  42. circle.color( 'yellow')
  43. circle.goto(-x, -y + 280)
  44. circle.stamp()
  45. circle.goto(x, -y + 280)
  46. circle.stamp()
  47. ​
  48. square.color( 'brown')
  49. for i in range( 13, 17):
  50. y = 30 * i
  51. for j in range( 2):
  52. x = 30 * j
  53. square.goto(x, -y + 280)
  54. square.stamp()
  55. square.goto(-x, -y + 280)
  56. square.stamp()

效果:

方法二:


  
  1. import turtle
  2. ​
  3. ​
  4. # 定义圣诞树的绿叶函数
  5. def tree(d, s):
  6. if d <= 0:
  7. return
  8. turtle.forward(s)
  9. tree(d - 1, s * .8)
  10. turtle.right( 120)
  11. tree(d - 3, s * .5)
  12. turtle.right( 120)
  13. tree(d - 3, s * .5)
  14. turtle.right( 120)
  15. turtle.backward(s)
  16. ​
  17. ​
  18. n = 100
  19. """ 设置绘图速度
  20. 'fastest' : 0
  21. 'fast' : 10
  22. 'normal' : 6
  23. 'slow' : 3
  24. 'slowest' : 1
  25. """
  26. turtle.speed( 'fastest') # 设置速度
  27. ​
  28. turtle.left( 90)
  29. turtle.forward( 3 * n)
  30. turtle.color( "orange", "yellow")
  31. turtle.left( 126)
  32. ​
  33. ​
  34. # turtle.begin_fill()
  35. for i in range( 5):
  36. turtle.forward(n / 5)
  37. turtle.right( 144)
  38. turtle.forward(n / 5)
  39. turtle.left( 72)
  40. turtle.end_fill()
  41. turtle.right( 126)
  42. turtle.color( "dark green")
  43. turtle.backward(n * 4.8)
  44. ​
  45. # 执行函数
  46. tree( 15, n)
  47. turtle.backward(n / 5)

效果:

 

 

 

IT入门 感谢关注

 

 

程序员题库→

程序员用的单词表→

练习地址:www.520mg.com/it

 

 


转载:https://blog.csdn.net/bigzql/article/details/110124594
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场