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 read函数按字节(字符)读取文件的实现

文件对象提供了 read() 方法来按字节或字符读取文件内容,到底是读取宇节还是字符,则取决于是否使用了 b 模式,如果使用了 b 模式,则每次读取一个字节;如果没有使用 b 模式,则每...

python实现SOM算法

python实现SOM算法

算法简介 SOM网络是一种竞争学习型的无监督神经网络,将高维空间中相似的样本点映射到网络输出层中的邻近神经元。 训练过程简述:在接收到训练样本后,每个输出层神经元会计算该样本与自身携带的...

python实现微信机器人: 登录微信、消息接收、自动回复功能

python实现微信机器人: 登录微信、消息接收、自动回复功能

安装wxpy pip install -U wxpy 登录微信 # 导入模块 from wxpy import * # 初始化机器人,扫码登陆 bot = Bot() 运行以...

Python wxpython模块响应鼠标拖动事件操作示例

Python wxpython模块响应鼠标拖动事件操作示例

本文实例讲述了Python wxpython模块响应鼠标拖动事件操作。分享给大家供大家参考,具体如下: wxpython鼠标拖动事件小案例: #coding:UTF-8 import...

Python延时操作实现方法示例

本文实例讲述了Python延时操作实现方法。分享给大家供大家参考,具体如下: 在日常的开发中,往往会遇到这样的需求,需要某一个函数在一段时间之后才执行以达到某种特定的效果。此时,我们就需...