Python+Turtle动态绘制一棵树实例分享

yipeiwu_com5年前Python基础

本文实例主要是对turtle的使用,实现Python+turtle动态绘制一棵树的实例,具体代码:

# drawtree.py
 
from turtle import Turtle, mainloop
 
def tree(plist, l, a, f):
  """ plist is list of pens
  l is length of branch
  a is half of the angle between 2 branches
  f is factor by which branch is shortened
  from level to level."""
  if l > 5: #
    lst = []
    for p in plist:
      p.forward(l)#沿着当前的方向画画Move the turtle forward by the specified distance, in the direction the turtle is headed.
      q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
      p.left(a) #Turn turtle left by angle units
      q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
      lst.append(p)#将元素增加到列表的最后
      lst.append(q)
    tree(lst, l*f, a, f)
  
      
 
def main():
  p = Turtle()
  p.color("green")
  p.pensize(5)
  #p.setundobuffer(None)
  p.hideturtle() #Make the turtle invisible. It's a good idea to do this while you're in the middle of doing some complex drawing,
  #because hiding the turtle speeds up the drawing observably.
  #p.speed(10)
  # p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
  p.speed(10)
  #TurtleScreen methods can then be called for that object.
  p.left(90)# Turn turtle left by angle units. direction 调整画笔
 
  p.penup() #Pull the pen up – no drawing when moving.
  p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle's orientation.
  p.pendown()# Pull the pen down – drawing when moving. 这三条语句是一个组合相当于先把笔收起来再移动到指定位置,再把笔放下开始画
  #否则turtle一移动就会自动的把线画出来
 
  #t = tree([p], 200, 65, 0.6375)
  t = tree([p], 200, 65, 0.6375)
   
main()

实现效果:

总结

以上就是本文关于Python+Turtle动态绘制一棵树实例分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python程序控制NAO机器人行走

最近重新学习nao的官方文档,写点简单的程序回顾一下。主要是用python调用api,写下来保存着。 '''Walk:small example to make nao walk''...

Python实现的购物车功能示例

Python实现的购物车功能示例

本文实例讲述了Python实现的购物车功能。分享给大家供大家参考,具体如下: 这里尝试用python实现简单的购物车程序。。。 基本要求: 用户输入工资,然后打印购物菜单 用户可以不断的...

python监控键盘输入实例代码

python监控键盘输入实例代码

本文研究的主要是python监控键盘输入的相关代码,用到了os,sys,time等,具体实现代码如下: #!/usr/bin/env python # -*- coding: u...

python字符串string的内置方法实例详解

下面给大家分享python 字符串string的内置方法,具体内容详情如下所示: #__author: "Pizer Wang" #__date: 2018/1/28 a = "Le...

用uWSGI和Nginx部署Flask项目的方法示例

用uWSGI和Nginx部署Flask项目的方法示例

概况 在开发过程中,我们一般直接用Python命令直接运行Flask程序。这样的运行只适合我们开发,方便我们调试。一旦程序部署到线上,这样运行的Flask程序性能会比较低。可以采用uW...