[Xiao Mu learns Python] Python realizes painting (turtle)

1 Introduction

Turtle drawing is very suitable to guide children to learn programming. Originally from the Logo programming language created in 1967 by Wally Feurzeig, Seymour Papert and Cynthia Solomon.

insert image description here

The turtle module provides basic components for drawing turtles in both object-oriented and procedural-oriented forms. Since it uses tkinter for its basic graphical interface, it requires a version of Python that supports Tk.

  • (1) Object-oriented interface
    Mainly use "2+2" classes:
    All methods of TurtleScreen/Screen also have corresponding functions, which are part of the process-oriented interface.
    All methods of RawTurtle/Turtle also have corresponding functions, i.e. as part of the procedure-oriented interface.
  • (2) Procedural interface
    The procedural interface provides functions corresponding to the methods of the Screen and Turtle classes. The function name is the same as the corresponding method name. When the corresponding function of the method of the Screen class is called, a Screen object will be created automatically. An (anonymous) Turtle object is automatically created when the corresponding function of the method of the Turtle class is called.

If you need to have multiple turtles on the screen, you must use an object-oriented interface.

2. Interface description

2.1 Turtle action

2.1.1 Moving and drawing

Order illustrate
forward() 、 fd() go ahead
backward() 、 bk() 、 back() step back
right() 、 rt() Turn right
left() 、 lt() Turn left
goto() 、 setpos() 、 setposition() go to/locate
setx() set the x-coordinate
sets() set the y coordinate
setheading()、 seth() set orientation
home() return to origin
circle() draw a circle
dot() draw dots
stamp() seal
clearstamp() clear stamp
clearstamps() Clear multiple stamps
undo() undo
speed() speed

2.1.2 Get the status of the turtle

Order illustrate
position() 、 pos() Location
towards() target direction
xcor() x-coordinate
ycor() y-coordinate
heading() toward
distance() distance

2.2 Brush Control

2.2.1 Drawing Status

Order illustrate
pendown() 、pd() 、down() brush drop
penup() 、 pu() 、 up() brush raised
pensize() 、 width() brush thickness
pen() brush
isdown() whether the brush falls

2.2.2 Color Control

Order illustrate
color() color
pencolor() brush color
fillcolor() fill color

2.2.3 Padding

Order illustrate
filling() Whether to fill
begin_fill() start filling
end_fill() end padding

2.2.4 More drawing controls

Order illustrate
reset() reset
clear() empty
write() write

2.3 TurtleScreen/Screen Method

2.3.1 Window Control

Order illustrate
bgcolor() background color
bgpic() Background picture
clearscreen() empty
resetscreen() reset
screensize() screen size
setworldcoordinates() Set the world coordinate system

2.3.2 Using screen events

Order illustrate
listen() monitor
onkey() 、onkeyrelease() When the keyboard is pressed and released
onkeypress() when the keyboard is pressed
onclick() 、 onscreenclick() when the screen is tapped
ontimer() when the timing is reached
mainloop()、done() main loop

2.3.3 Screen proprietary methods

Order illustrate
bye() quit
exitonclick() exit when clicked
setup() set up
title() title

3. Example test

3.1 Turtle star

from turtle import *
title('turtle绘图 - 爱看书的小沐')
color('red', 'yellow')
speed(10)
begin_fill()
while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break
end_fill()
done()

or

import turtle as t
# import time
t.color("red", "yellow")
t.speed(10)
t.begin_fill()
for _ in range(50):
    t.forward(200)
    t.left(170)
t.end_fill()
# time.sleep(1)
t.done()

insert image description here

3.2 Fractal Trees

# -*- coding: utf-8 -*-

import turtle

toplevel = 8  # 一共递归8层
angle = 30
rangle = 15


def drawTree(length, level):
    turtle.left(angle)  # 绘制左枝
    turtle.color("black")
    turtle.forward(length)

    if level == toplevel:  # 叶子
        turtle.color("pink")
        turtle.circle(2, 360)

    if level < toplevel:  # 在左枝退回去之前递归
        drawTree(length - 10, level + 1)
    turtle.back(length)

    turtle.right(angle + rangle)  # 绘制右枝
    turtle.color("black")
    turtle.forward(length)

    if level == toplevel:  # 叶子
        turtle.color("pink")
        turtle.circle(2, 360)

    if level < toplevel:  # 在右枝退回去之前递归
        drawTree(length - 10, level + 1)
        turtle.color("black")
    turtle.back(length)
    turtle.left(rangle)

def writePoem():
    turtle.color("blue")
    turtle.penup()
    turtle.goto(150, -120)
    turtle.write('碧玉妆成一树高,',font=("隶书", 15))
    turtle.goto(150, -140)
    turtle.write('万条垂下绿丝绦。',font=("隶书", 15))
    turtle.goto(150, -160)
    turtle.write('不知细叶谁裁出,',font=("隶书", 15))
    turtle.goto(150, -180)
    turtle.write('二月春风似剪刀。',font=("隶书", 15))
    turtle.hideturtle()

turtle.left(90)
turtle.penup()
turtle.back(300)
turtle.pendown()
turtle.forward(100)
# turtle.speed('fastest')
turtle.speed(11)
# drawTree(80, 1)
drawTree(80, 1)
writePoem()

turtle.done()

insert image description here

3.3 Ballooning


from turtle import *
from random import randrange,choice
 
balloons=[]   #气球队列
color_option=["red","blue","green","purple","pink","yellow","orange","black"]   #颜色队列
size=50   #气球大小

def line(x,y,a,b,line_width=1,color_name="black"):   #默认气球线宽度为1,颜色为黑
    up()
    goto(x,y)
    down()
    color(color_name)
    width(line_width)
    goto(a,b)

def distance(x,y,a,b):
    return ((a-x)**2+(b-y)**2)**0.5   #根据勾股定理,判断鼠标点击位置和气球坐标的距离

def tap(x,y):
    for i in range(len(balloons)):
        if distance(x,y,balloons[i][0],balloons[i][1])<(size/2):   #判断是否点击气球队列中的其中一个
            balloons.pop(i)   #删除这个气球
            return   #返回,因为只能同时点击一个气球

def draw():
    clear()   #清除画布
    for i in range(1,(len(balloons)+1)):   #生成下标从1开始,以下-i表示画气球时倒着画,从最后一个画到最前边
        line(balloons[-i][0],balloons[-i][1],balloons[-i][0],balloons[-i][1]-size*1.5,1)
        up()   #把小乌龟从画布上拿下来,悬在空中
        goto(balloons[-i][0],balloons[-i][1])   #去气球坐标这个位置
        dot(size,balloons[-i][2])   #画原点,参数为大小和颜色
        balloons[-i][1]=balloons[-i][1]+1   #改变纵坐标,模仿气球上升
    update()   #修改画布
def gameLoop():
    if randrange(0,50)==1:   #1/50的概率生成一个气球
        x=randrange(-200+size,200-size)   #气球坐标,在边框位置减去气球大小
        c=choice(color_option)   #随机在颜色队列选择一个颜色
        balloons.append([x,-200-size,c])   #添加气球队列
    draw()
    ontimer(gameLoop,10)   #每20毫秒循环一次

if __name__ == "__main__":
    setup(600, 350, 0, 0)   #画布大小为420*420,一开始坐标为(0,0)
    bgpic(r'C:\Users\tomcat\desktop\20220919041856.png')
    hideturtle()   #隐藏小乌龟
    tracer(False)   #隐藏绘制过程
    listen()
    onscreenclick(tap)   #如果单机,调用tap方法
    gameLoop()
    done()   #结束函数,画布停留

insert image description here

3.4 turtledemo — collection of demo scripts

The turtledemo package is a collection of demo scripts. These scripts can be run and viewed by opening the provided demo viewer with the following command:

python -m turtledemo
# or
python -m turtledemo.bytedesign

insert image description here

epilogue

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)// ,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!(´▽´)ノ (´▽´)! ! !

Guess you like

Origin blog.csdn.net/hhy321/article/details/131142412