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之——生成动态路由轨迹图的实例

Python之——生成动态路由轨迹图的实例

一、scapy简介与安装 scapy(http://www.secdev.org/projects/scapy/)是一个强大的交互式数据包处理程序,它能够对数据包进行伪造或解包,包括发送...

python中enumerate函数用法实例分析

本文实例讲述了python中enumerate函数用法。分享给大家供大家参考。具体分析如下: 今日发现一个新函数 enumerate 。一般情况下对一个列表或数组既要遍历索引又要遍历元素...

python格式化输出保留2位小数的实现方法

python格式化输出保留2位小数的实现方法

我是小白就不用多说了,学习python做了个练习题,结果运行了一遍,发现输入金额后得到的有很多位小数, 虽然不知道为什么,但是看得很不舒服, 就想到应该把让小数点后只保留2位数 找到了方...

Python 实现域名解析为ip的方法

今天得了一批域名,需要把域名解析成ip 因为量比较大所以采用了多进程和队列的方式 from multiprocessing import Process,Queue,Pool imp...

python中计算一个列表中连续相同的元素个数方法

最简单的例子: a = [1,1,1,1,2,2,2,3,3,1,1,1,3] # 问:计算a中最多有几个连续的1 很明显,答案是4 如果用代码实现,最先想到的就是itertool...