聊点易乐谷turtle
.
about turtle
turtle
1是个颇具亲切感的库, 它会让你想到小学时坐在微机教室跟着老师的指导玩的易乐谷(ELOGO
)2 (而其实易乐谷也是基于MSWLOGO
的), 如若我没记错的话易乐谷也是一个写程式绘图的工具软件, 而且上面爬的不是海龟君而是一只瓢虫君3:
简单记一点单个脚本使用一次turtle
的基本方法:
Methods | Aliases | Description |
---|---|---|
.setup(width=0.5, height=0.75, startx=None, starty=None) |
Set the size and position of the main window. 用于创建画布的方法 |
|
.color(*args) |
Return or set the pencolor and fillcolor. 用于设定笔触颜色与填充颜色的方法, 仅传入一个参数时用途等同于 .pencolor() , 可以设置笔触颜色,传入两个参数时前者设定笔触颜色, 后者设定填充颜色 |
|
.pencolor(*args) |
Return or set the pencolor. 用于获取或设定笔触颜色的方法 |
|
.fillcolor(*args) |
Return or set the fillcolor. 用于获取或设定填充颜色的方法 |
|
.begin_fill() |
Called just before drawing a shape to be filled. 声明开始填充颜色 |
|
.end_fill() |
Fill the shape drawn after the call .begin_fill() .在上一次 .begin_fill() 之后到本次.end_fill() 之间所绘制线条围成的封闭区域被填充.color() 或.fillcolor() 所指定的颜色 |
|
.pensize(width=None) |
.width() |
Set or return the line Thickness. 设定或获取笔触宽度 |
.penup() |
.pu() .up() |
Pull the pen up — no drawing when moving. 提笔, 暂时不进行绘制 |
.pendown() |
.pd() .down() |
Pull the pen down — drawing when moving. 落笔, 重新继续绘制 |
.forward(distance) |
.fd() |
Move the turtle forward by the specified distance. 前进 |
.setheading(to_angle) |
.seth() |
Set the orientation of the turtle to to_angle. 设置前进朝向, 默认水平向右, 设置朝向为水平右向加 to_angle 的角度值 |
.circle(radius, extent=None, steps=None) |
Draw a circle with given radius. 绘制圆或圆弧, radius 指定半径,如若绘制圆弧则可以用 extent 指定其圆心角,steps 用于绘制圆弧内接折线时指定折现的段数 |
|
.mainloop() |
.done() |
Starts event loop - calling Tkinter’s mainloop function. 使呼出的窗体进入 mainloop |
这里需要简单说明一下.mainloop()
.
这个函数需要在绘图结束时调用, 其原因在于turtle
绘图呼出的窗体是基于TkInter
4 (另一个Python
标准库)实现的, 那是Python
对GUI框架Tcl/Tk
5的接口.
而Tk
的窗体完成构建之后运行的过程可以大致理解为mainloop
, 这个时候其等待用户对窗体的动作, 解释为不同种类的事件, 并作出反应.
如若不进入mainloop
而直接开始对窗体进行操作, 则常容易使之卡死.
如上所言, 我们可以得知使用turtle
进行简单绘图时的大致流程如下
1 | import turtle # 导入turtle模块 |
现在我们大致画一个分段彩色蟒蛇, 程式如下
1 | #!/usr/bin/env Python |
运行结果大致如下
References
1.turtle
: Turtle graphics - Python 3 Documentation
(forPython 3.6
: https://docs.python.org/3.6/library/turtle.html) ↩
2. 百度百科词条 易乐谷 ↩
3. 百度知道问答 易乐谷的介绍 ↩
4.tkinter
:Python
interface toTcl/Tk
- Python 3 Documentation
(forPython 3.6
: https://docs.python.org/3.6/library/tkinter.html) ↩
5.Tcl
Developer Site
(Another: https://www.tcl-lang.org/)
(Document: https://tkdocs.com/index.html) ↩