flag.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """
  2. 用Python的turtle模块绘制国旗
  3. """
  4. import turtle
  5. def draw_rectangle(x, y, width, height):
  6. """绘制矩形"""
  7. turtle.goto(x, y)
  8. turtle.pencolor('red')
  9. turtle.fillcolor('red')
  10. turtle.begin_fill()
  11. for i in range(2):
  12. turtle.forward(width)
  13. turtle.left(90)
  14. turtle.forward(height)
  15. turtle.left(90)
  16. turtle.end_fill()
  17. def draw_star(x, y, radius):
  18. """绘制五角星"""
  19. turtle.setpos(x, y)
  20. pos1 = turtle.pos()
  21. turtle.circle(-radius, 72)
  22. pos2 = turtle.pos()
  23. turtle.circle(-radius, 72)
  24. pos3 = turtle.pos()
  25. turtle.circle(-radius, 72)
  26. pos4 = turtle.pos()
  27. turtle.circle(-radius, 72)
  28. pos5 = turtle.pos()
  29. turtle.color('yellow', 'yellow')
  30. turtle.begin_fill()
  31. turtle.goto(pos3)
  32. turtle.goto(pos1)
  33. turtle.goto(pos4)
  34. turtle.goto(pos2)
  35. turtle.goto(pos5)
  36. turtle.end_fill()
  37. def main():
  38. """主程序"""
  39. turtle.speed(12)
  40. turtle.penup()
  41. x, y = -270, -180
  42. # 画国旗主体
  43. width, height = 540, 360
  44. draw_rectangle(x, y, width, height)
  45. # 画大星星
  46. pice = 22
  47. center_x, center_y = x + 5 * pice, y + height - pice * 5
  48. turtle.goto(center_x, center_y)
  49. turtle.left(90)
  50. turtle.forward(pice * 3)
  51. turtle.right(90)
  52. draw_star(turtle.xcor(), turtle.ycor(), pice * 3)
  53. x_poses, y_poses = [10, 12, 12, 10], [2, 4, 7, 9]
  54. # 画小星星
  55. for x_pos, y_pos in zip(x_poses, y_poses):
  56. turtle.goto(x + x_pos * pice, y + height - y_pos * pice)
  57. turtle.left(turtle.towards(center_x, center_y) - turtle.heading())
  58. turtle.forward(pice)
  59. turtle.right(90)
  60. draw_star(turtle.xcor(), turtle.ycor(), pice)
  61. # 隐藏海龟
  62. turtle.ht()
  63. # 显示绘图窗口
  64. turtle.mainloop()
  65. if __name__ == '__main__':
  66. main()