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动态绘制一棵树实例分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Mac下Anaconda的安装和使用教程

前提 在刚接触python的时候我想大多数人都会面临一个问题,我到底是选择2还是3,因为现在网上好多的资料和视频项目中都还是用的2,我们跟着学习的时候肯定也是首先从2开始学的,但是我们心...

详谈python3 numpy-loadtxt的编码问题

如下所示: data_array = np.loadtxt(filename, #文件名 delimiter=',', #分隔符...

Python3实现的腾讯微博自动发帖小工具

复制代码 代码如下:# -*- coding: UTF-8 -*-import mysql.connector as dbimport client.tWeiboimport time...

Python标准库itertools的使用方法

Python标准库itertools模块介绍 itertools是python内置的模块,使用简单且功能强大,这里尝试汇总整理下,并提供简单应用示例;如果还不能满足你的要求,欢迎加入...

Python实现的数据结构与算法之队列详解

Python实现的数据结构与算法之队列详解

本文实例讲述了Python实现的数据结构与算法之队列。分享给大家供大家参考。具体分析如下: 一、概述 队列(Queue)是一种先进先出(FIFO)的线性数据结构,插入操作在队尾(rear...