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

yipeiwu_com6年前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 中的with关键字使用详解

在 Python 2.5 中, with 关键字被加入。它将常用的 try ... except ... finally ... 模式很方便的被复用。看一个最经典的例子: with...

跟老齐学Python之字典,你还记得吗?

字典,这个东西你现在还用吗?随着网络的发展,用的人越来越少了。不少人习惯于在网上搜索,不仅有web版,乃至于已经有手机版的各种字典了。我曾经用过一本小小的《新华字典》。 《新华字典》是中...

python Elasticsearch索引建立和数据的上传详解

python Elasticsearch索引建立和数据的上传详解

今天我想讲一讲关于Elasticsearch的索引建立,当然提前是你已经安装部署好Elasticsearch。 ok,先来介绍一下Elaticsearch,它是一款基于lucene的实时...

Python基于Logistic回归建模计算某银行在降低贷款拖欠率的数据示例

Python基于Logistic回归建模计算某银行在降低贷款拖欠率的数据示例

本文实例讲述了Python基于Logistic回归建模计算某银行在降低贷款拖欠率的数据。分享给大家供大家参考,具体如下: 一、Logistic回归模型:   二、Logisti...

python3使用smtplib实现发送邮件功能

python3使用smtplib实现发送邮件功能

在之前的工作中,业务方做了一些调整,提出了对一部分核心指标做更细致的拆分并定期产出的需求。出于某些原因,这部分数据不太方便在报表上呈现,因此就考虑通过邮件的方式定期给业务方发送数据。 当...