Python Lesson II

Author: sandyzikun

聊点易乐谷turtle.

about turtle

turtle1是个颇具亲切感的库, 它会让你想到小学时坐在微机教室跟着老师的指导玩的易乐谷(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绘图呼出的窗体是基于TkInter4 (另一个Python标准库)实现的, 那是Python对GUI框架Tcl/Tk5的接口.
Tk的窗体完成构建之后运行的过程可以大致理解为mainloop, 这个时候其等待用户对窗体的动作, 解释为不同种类的事件, 并作出反应.
如若不进入mainloop而直接开始对窗体进行操作, 则常容易使之卡死.

如上所言, 我们可以得知使用turtle进行简单绘图时的大致流程如下

Python
1
2
3
4
5
import turtle # 导入turtle模块

turtle.setup() # (其实是可选的)创建画布
... # 绘图过程
turtle.mainloop() # 使turtle呼出的窗体进入mainloop

现在我们大致画一个分段彩色蟒蛇, 程式如下

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env Python
# -*- coding: utf-8 -*-

"""
@author: 陈 子坤 (GitHub@sandyzikun)
@title: Instance 01-2 使用Python的Turtle模块,绘制彩色蟒蛇
@time: 2022-03-17 14:39
"""

# Importing Python Modules / 导入Python相关模块
import turtle

# Constants / 声明需要的常量
class Base16Solarized(object): # Solarized by GitHub@altercation
BASES = {
"00": "#002b36",
"07": "#fdf6e3",
}
COLORS = {
"yellow": "#b58900",
"orange": "#cb4b16",
"red": "#dc322f",
"magenta": "#d33682",
"violet": "#6c71c4",
"blue": "#268bd2",
"cyan": "#2aa198",
"green": "#859900",
}
class Constants(object):
CANVAS_POSITION = (650, 350, 720, 200)
DISTANCE_INITIAL_MOVING = -250
DEFAULT_PENSIZE = 25
BIAS_ANGLE = 39
NUM_PHASES = 4
LEN_HEAD = 39
LEN_NECK = 15.6

def init(): # The Main Function / 主函数
# Initialization / 初始化
turtle.setup(Constants.CANVAS_POSITION[0], Constants.CANVAS_POSITION[1], Constants.CANVAS_POSITION[2], Constants.CANVAS_POSITION[3]) # Setting Position & Scale of Canvas / 设置画布的位置与尺寸
# About Color-Control of Turtle: https://docs.python.org/3.6/library/turtle.html#color-control
turtle.pencolor(Base16Solarized.BASES["00"]) # Setting Colors of Foreground / 设置前景颜色
turtle.screensize(bg = Base16Solarized.BASES["07"]) # Setting Colors of Background / 设置背景颜色

turtle.penup() # Temporarily Disable the Drawing Function / 提笔
turtle.forward(Constants.DISTANCE_INITIAL_MOVING) # Move Left to the Initial Position / 向左移至初始位置

turtle.pendown() # Enable the Drawing Function / 落笔
turtle.pensize(Constants.DEFAULT_PENSIZE) # Setting the Pensize / 设置笔触大小
turtle.pencolor(Base16Solarized.COLORS["violet"]) # Setting the Pencolor / 设置笔触颜色
turtle.setheading(Constants.BIAS_ANGLE * (-1)) # Setting the Initial Direction / 设置初始方向偏角

for eachkey in [ "red", "cyan", "yellow", "blue" ]: # Colors of Each Phase / 各段的颜色
turtle.pencolor(Base16Solarized.COLORS[eachkey]) # Setting the Pencolor / 设置笔触颜色
# Drawing "the Body" as Arcs / 以圆弧形式绘制蛇体
turtle.circle(Constants.BIAS_ANGLE, Constants.BIAS_ANGLE * 2)
turtle.circle(Constants.BIAS_ANGLE * (-1), Constants.BIAS_ANGLE * 2)

turtle.pencolor(Base16Solarized.COLORS["violet"]) # Returning to the Default Pencolor / 恢复笔触颜色
# Drawing "the Neck" & "the Head" / 绘制脖颈及头部
turtle.circle(Constants.BIAS_ANGLE, Constants.BIAS_ANGLE)
turtle.forward(Constants.LEN_HEAD)
turtle.circle(Constants.LEN_NECK, 180)
turtle.forward(Constants.LEN_HEAD * 2 / 3)

# Waiting for Manually Exit / 等待手动退出
turtle.mainloop()

if __name__ == "__main__":
init()

运行结果大致如下

References

1. turtle: Turtle graphics - Python 3 Documentation
(for Python 3.6: https://docs.python.org/3.6/library/turtle.html)
2. 百度百科词条 易乐谷
3. 百度知道问答 易乐谷的介绍
4. tkinter: Python interface to Tcl/Tk - Python 3 Documentation
(for Python 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)