Function usage of turtle library in python, python turtle library function drawing

This article mainly introduces where to check the usage of pythonturtle library functions. It has certain reference value. Friends in need can refer to it. I hope you will gain a lot after reading this article. Let the editor take you to understand it together.

Turtle drawing:

turtle official documentation

Overview

Turtle drawings are great for introducing children to programming. All arithmetic symbols in Python, the Logo programming language originally created by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967 .

Please imagine that there is a robot turtle in the drawing area, and its starting position is at the (0, 0) point on the xy plane. Execute import turtle first, and then execute turtle.forward(15). It will advance 15 pixels (on the screen) in the positive direction of the x-axis it is facing, and draw a line segment as it moves. Execute turtle.right(25) again, and it will turn 25 degrees to the right.
Using Turtle Drawing, you can write programs that repeatedly perform simple actions to draw elaborate and complex shapes.
By combining such commands, you can easily draw beautiful shapes and patterns.
The turtle module is rewritten based on the module of the same name since Python standard release version 2.5 and has expanded functionality.
The new module maintains the features of the original module as much as possible and is (almost) 100% compatible with it. This means that novice programmers can interactively use all commands, classes and methods of the module - pay attention to adding the -n parameter when running IDLE.
The turtle module provides basic components for turtle drawing in both object-oriented and procedural forms. Since it uses tkinter to implement the basic graphical interface, a Python version supported by Tk needs to be installed.

turtle method

turtle action

Move and draw
forward() | fd() 前进
backward() | bk() | back() 后退
right() | rt() 右转
left() | lt() 左转
goto() | setpos() | setposition() 前往/定位
setx() 设置x坐标
sety() 设置y坐标
setheading() | seth() 设置朝向
home() 返回原点
circle() 画圆
dot() 画点
stamp() 印章
clearstamp() 清除印章
clearstamps() 清除多个印章
undo() 撤消
speed() 速度
Get the status of the turtle
position() | pos() 位置
towards() 目标方向
xcor() x坐标
ycor() y坐标
heading() 朝向
distance() 距离
Settings and units of measurement
degrees() 角度
radians() 弧度

Brush control

drawing control
pendown() | pd() | down() 画笔落下
penup() | pu() | up() 画笔抬起
pensize() | width() 画笔粗细
pen() 画笔
isdown() 画笔是否落下
Color control
color() 颜色
pencolor() 画笔颜色
fillcolor() 填充颜色
filling
filling() 是否填充
begin_fill() 开始填充
end_fill() 结束填充
More drawing controls
reset() 重置
clear() 清空
write() 书写

turtle status

visibility
showturtle() | st() 显示海龟
hideturtle() | ht() 隐藏海龟
isvisible() 是否可见
Exterior
shape() 形状
resizemode() 大小调整模式
shapesize() | turtlesize() 形状大小
shearfactor() 剪切因子
settiltangle() 设置倾角
tiltangle() 倾角
tilt() 倾斜
shapetransform() 变形
get_shapepoly() 获取形状多边形

Use events

onclick() 当鼠标点击
onrelease() 当鼠标释放
ondrag() 当鼠标拖动

Special turtle method

begin_poly() 开始记录多边形
end_poly() 结束记录多边形
get_poly() 获取多边形
clone() 克隆
getturtle() | getpen() 获取海龟画笔
getscreen() 获取屏幕
setundobuffer() 设置撤消缓冲区
undobufferentries() 撤消缓冲区条目数

TurtleScreen/Screen method

window control

bgcolor() 背景颜色
bgpic() 背景图片
clear() | clearscreen() 清屏
reset() | resetscreen() 重置
screensize() 屏幕大小
setworldcoordinates() 设置世界坐标系

animation control

delay() 延迟
tracer() 追踪
update() 更新

Use screen events

listen() 监听
onkey() | onkeyrelease() 当键盘按下并释放
onkeypress() 当键盘按下
onclick() | onscreenclick() 当点击屏幕
ontimer() 当达到定时
mainloop() | done() 主循环

Settings and special methods

mode() 模式
colormode() 颜色模式
getcanvas() 获取画布
getshapes() 获取形状
register_shape() | addshape() 添加形状
turtles() 所有海龟
window_height() 窗口高度
window_width() 窗口宽度

Input method

textinput() 文本输入
numinput() 数字输入

Screen-specific methods

bye() 退出
exitonclick() 当点击时退出
setup() 设置
title() 标题

Turtle methods and corresponding functions

turtle action

go ahead

turtle.forward(ditance)
turtle.fd(distance)

The turtle moves forward the distance specified by distance, in the direction of the turtle.

>>> turtle.position()
(0.00,0.00)
>>> turtle.forward(25)
>>> turtle.position()
(25.00,0.00)
>>> turtle.forward(-75)
>>> turtle.position()
(-50.00,0.00)

Back
The turtle retreats a distance specified by distance, in the opposite direction to the turtle's direction. Does not change the turtle's orientation.

turtle.back(distance)
turtle.bk(distance)
turtle.backward(distance)
>>> turtle.position()
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)

Turn left

turtle.right(angle)
turtle.rt(angle)

The turtle turns right angle units. (The units default to degrees, but this can be changed with the degrees() and radians() functions.) The sign of the angle is determined by the turtle mode, see mode().

>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0

Turn right

turtle.left(angle)
turtle.lt(angle)

The turtle turns left angle units. (The units default to degrees, but this can be changed with the degrees() and radians() functions.) The sign of the angle is determined by the turtle mode, see mode().

>>> turtle.heading()
22.0
>>> turtle.left(45)
>>> turtle.heading()
67.0

Fixed point movement

turtle.goto(x, y=None)
turtle.setpos(x, y=None)
turtle.setposition(x, y=None)

If y is None, x should be a numeric pair representing coordinates or a Vec2D class object (such as the object returned by pos()).

The turtle moves to an absolute coordinate. A line will be drawn if the pen is down. Does not change the turtle's orientation.

 >>> tp = turtle.pos()
 >>> tp
 (0.00,0.00)
 >>> turtle.setpos(60,30)
 >>> turtle.pos()
 (60.00,30.00)
 >>> turtle.setpos((20,80))
 >>> turtle.pos()
 (20.00,80.00)
 >>> turtle.setpos(tp)
 >>> turtle.pos()
 (0.00,0.00)

Set the abscissa:
Set the turtle's abscissa to x, and keep the ordinate unchanged.

turtle.setx(x)

>>> turtle.position()
(0.00,240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00,240.00)

Set the vertical coordinate.
Set the vertical coordinate of the turtle to y, and keep the horizontal coordinate unchanged.

turtle.sety(y)

>>> turtle.position()
(0.00,40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00,-10.00)

Set the turtle's angle
Set the turtle's orientation to to_angle. Here are a few common directions expressed in angles:
Insert image description here

turtle.setheading(to_angle)
turtle.seth(to_angle)¶

>>> turtle.setheading(90)
>>> turtle.heading()
90.0

The turtle returns home.
The turtle moves to the initial coordinate (0,0) and sets the orientation as the initial direction (determined by the turtle mode, see mode()).

turtle.home()

>>> turtle.heading()
90.0
>>> turtle.position()
(0.00,-10.00)
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0

Turtle Draw Circle
Draws a circle with radius specified by radius. The center of the circle is radius units to the left of the turtle; extent is an angle used to determine the portion of the circle to be drawn. If extent* is not specified, the entire circle is drawn. If *extent is not a complete circle, an arc is drawn with the current pen position as one endpoint. If radius is positive, the arc is drawn counterclockwise, otherwise clockwise. Eventually the turtle's orientation will change based on the extent value.

A circle is actually approximately represented by its inscribed regular polygon, with the number of sides specified by steps. If the number of sides is not specified it will be determined automatically. This method can also be used to draw regular polygons.

turtle.circle(radius, extent=None, steps=None)

radius – a number
extent – ​​a number (or None)
steps – an integer (or None)

>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(50)
>>> turtle.position()
(-0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(120, 180)  # draw a semicircle
>>> turtle.position()
(0.00,240.00)
>>> turtle.heading()
180.0

Turtle Drawing Point
Draws a dot with diameter size and color color. If size is not specified, the diameter takes the larger of pensize+4 and 2*pensize.

turtle.dot(size=None, *color)

size – an integer >= 1 (if specified)
color – a color string or tuple of color values

>>> turtle.home()
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
>>> turtle.position()
(100.00,-0.00)
>>> turtle.heading()
0.0

Turtle Stamp
Prints a turtle shape at the turtle's current location. Returns the stamp_id of the stamp. The stamp can be deleted by calling clearstamp(stamp_id).

turtle.stamp()

>>> turtle.color("blue")
>>> turtle.stamp()
11
>>> turtle.fd(50)

Turtle Clearance Stamp

turtle.clearstamp(stampid)
#stampid -- 一个整型数,必须是之前 stamp() 调用的返回值

Delete the stamp specified by stampid.

>>> turtle.position()
(150.00,-0.00)
>>> turtle.color("blue")
>>> astamp = turtle.stamp()
>>> turtle.fd(50)
>>> turtle.position()
(200.00,-0.00)
>>> turtle.clearstamp(astamp)
>>> turtle.position()
(200.00,-0.00)
turtle.clearstamps(n=None)
#n -- 一个整型数 (或 None)

Delete all or the first/last n turtle stamps. If n is None, delete all seals. If n > 0, delete the first n seals. Otherwise, if n < 0, delete the last n seals.

>>> for i in range(8):
...     turtle.stamp(); turtle.fd(30)
13
14
15
16
17
18
19
20
>>> turtle.clearstamps(2)
>>> turtle.clearstamps(-2)
>>> turtle.clearstamps()

Undo turtle action

turtle.undo()

Undo (or continuously undo) the most recent turtle action(s). The number of times you can undo is determined by the size of the undo buffer.

>>> for i in range(4):
...     turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
...     turtle.undo()

Control turtle speed

turtle.speed(speed=None)
#speed -- 一个 0..10 范围内的整型数或速度字符串 (见下)

Set the turtle's moving speed to an integer value represented by 0...10. If no parameters are specified, the current speed is returned.

If the entered value is greater than 10 or less than 0.5 the speed is set to 0. The corresponding relationship between speed string and speed value is as follows:

"fastest": 0 fastest

"fast": 10 fast

"normal": 6 normal

"slow": 3 slow

"slowest": 1 slowest

Speed ​​values ​​from 1 to 10 animate the drawing of lines and the turtle's turns faster and faster.

Note: speed = 0 means no animation effect. forward/back will make the turtle jump forward/backward, and the same left/right will make the turtle change direction immediately.

>>> turtle.speed()
3
>>> turtle.speed('normal')
>>> turtle.speed()
6
>>> turtle.speed(9)
>>> turtle.speed()
9

Get turtle status

Turtle's current location

turtle.position()
turtle.pos()¶

Returns the current coordinates (x, y) of the turtle (which is a Vec2D vector class object).

>>> turtle.pos()
(440.00,-0.00)

Find the angle between the turtle and the set position

turtle.towards(x, y=None)¶
#x -- 一个数值或数值对/矢量,或一个海龟实例
#y -- 一个数值——如果 x 是一个数值,否则为 None

The angle from the turtle's position to the line connected by (x,y), the vector, or the corresponding position of another turtle. This value depends on the turtle's initial orientation - determined by the "standard"/"world" or "logo" mode settings).

>>> turtle.goto(10, 10)
>>> turtle.towards(0,0)
225.0

Returns the current x-axis coordinate of the turtle

turtle.xcor()
>>> turtle.home()
>>> turtle.left(50)
>>> turtle.forward(100)
>>> turtle.pos()
(64.28,76.60)
>>> print(round(turtle.xcor(), 5))
64.27876

Returns the current y-axis coordinate of the turtle

turtle.ycor()
>>> turtle.home()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print(turtle.pos())
(50.00,86.60)
>>> print(round(turtle.ycor(), 5))
86.60254

Returns the turtle's current heading

turtle.heading()
>>> turtle.home()
>>> turtle.left(67)
>>> turtle.heading()
67.0

Returns the absolute distance between the current point and a given point

turtle.distance(x,y)
#x -- 一个数值或数值对/矢量,或一个海龟实例
#y -- 一个数值——如果 x 是一个数值,否则为 None
>>> turtle.home()
>>> turtle.distance(30,40)
50.0
>>> turtle.distance((30,40))
50.0
>>> joe = Turtle()
>>> joe.forward(77)
>>> turtle.distance(joe)
77.0

Measurement unit settings

Set the unit of measurement for angles

turtle.degrees(fullcircle=360.0)

Set the unit of measurement for angles, that is, set the number of "degrees" for a circle. The default value is 360 degrees.在这里插入代码片

>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0

Change angle measurement unit to grad (also known as gon,
grade, or gradian and equals 1/100-th of the right angle.)
>>> turtle.degrees(400.0)
>>> turtle.heading()
100.0
>>> turtle.degrees(360)
>>> turtle.heading()
90.0

Set angle to radians

turtle.radians()

Sets the angle measurement unit to radians. Its value is equal to degrees(2*math.pi).

>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0
>>> turtle.radians()
>>> turtle.heading()
1.5707963267948966

Brush control

drawing status

#抬笔
turtle.penup()
turtle.pu()
turtle.up()
#落笔
turtle.pendown()
turtle.pd()
turtle.down()
#画笔粗细
turtle.pensize(width=None)¶
turtle.width(width=None)

Brush settings

turtle.pen(pen=None, **pendict)
#pen -- 一个包含部分或全部下列键的字典
#pendict -- 一个或多个以下列键为关键字的关键字参数

Returns or sets the properties of the brush, represented by a "brush dictionary" containing the following key-value pairs:

“shown”: True/False

“pendown”: True/False

"pencolor": color string or color tuple

"fillcolor": color string or color tuple

"pensize": positive value

"speed": a value in the range 0…10

"resizemode": "auto" or "user" or "noresize"

"stretchfactor": (positive value, positive value)

"outline": positive value

"tilt": numerical value

This dictionary can be used as an argument to subsequent calls to pen() to restore the previous pen state. These attributes can also be submitted as keyword parameters. Use this method to set multiple properties of the brush with one statement.

>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
>>> sorted(turtle.pen().items())
[('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
 ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
 ('shearfactor', 0.0), ('shown', True), ('speed', 9),
 ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]
>>> penstate=turtle.pen()
>>> turtle.color("yellow", "")
>>> turtle.penup()
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')]
>>> turtle.pen(penstate, fillcolor="green")
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]

Did the brush fall?turtle.isdown()

Color control

Get turtle status

Third-level directory

Guess you like

Origin blog.csdn.net/mynote/article/details/133549170