How do you draw with the turtle module in Python?

To draw shapes with the turtle module, you first need to import the turtle module and then call the appropriate functions to draw the shapes. Here is a simple example demonstrating how to use the turtle module to draw a square.

import turtle

# 创建一个Turtle对象
t = turtle.Turtle()

# 绘制正方形
for _ in range(4):
    t.forward(100)  # 向前移动100个像素
    t.right(90)  # 向右转动90度

# 关闭绘图窗口
turtle.done()

Running the code above will draw a square with a side length of 100. You can use different turtle functions to draw various shapes according to your needs. For example, t.forward(distance) is used to move forward a certain distance, and t.right(angle) is used to turn right by a certain angle. After drawing the shape, use turtle.done() to keep the drawing window displayed.

bannerAds