Turtle là thư viện Python vẽ đồ họa. Sau khi import, ta ra lệnh: forward, backward, right, left... Kết hợp các lệnh tạo hình ảnh đẹp.
Các lệnh Turtle cơ bản
- forward(10): tiến 10 pixel.
- backward(5): lùi 5 pixel.
- right(35): xoay phải 35 độ.
- left(55): xoay trái 55 độ.
- goto(x, y): di chuyển đến tọa độ (x, y).
- dot(): vẽ chấm tại vị trí hiện tại.
- shape('circle'): vẽ hình tròn.
Ví dụ: Vẽ ngôi sao
import turtle
star = turtle.Turtle()
for i in range(100):
star.forward(100)
star.right(144)
turtle.done()

Ví dụ: Vẽ chữ E
import turtle
t = turtle.Turtle()
t.penup()
t.setpos(-20, 40)
t.pendown()
t.pensize(10)
t.pencolor("pink")
t.forward(100)
t.backward(100)
t.right(90)
t.forward(100)
t.left(90)
t.forward(100)
t.backward(100)
t.right(90)
t.forward(100)
t.left(90)
t.forward(100)
turtle.done()

Ví dụ: Nhiều vuông góc chung đỉnh
import turtle
mult_square = turtle.Turtle()
def Multiple_Squares(length, colour):
mult_square.pencolor(colour)
mult_square.pensize(2)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.setheading(360)
for i in range(60, 120, 15):
Multiple_Squares(i, "blue")
turtle.done()

Ví dụ: Lục giác xoáy màu
import turtle
colors = ["pink", "yellow", "blue", "green", "white", "red"]
sketch = turtle.Pen()
turtle.bgcolor("black")
for i in range(200):
sketch.pencolor(colors[i % 6])
sketch.width(i/100 + 1)
sketch.forward(i)
sketch.left(59)
