You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Turtle绘制10×10点阵时额外间隙问题排查

Turtle绘制10×10点阵的间隙问题分析与解决

问题原因

你遇到的间隙问题,核心原因是turtle.circle()函数的绘制特性:

  • 当海龟朝东(0°)时,circle(10)会以海龟左侧(北侧)为圆心绘制逆时针圆,圆的底部对齐海龟当前位置,圆心在海龟位置的正上方(y+10)。
  • 当海龟朝西(180°)时,circle(10)以海龟左侧(南侧)为圆心绘制逆时针圆,圆的顶部对齐海龟当前位置,圆心在海龟位置的正下方(y-10)。

这种朝向导致的圆位置偏移,使得相邻两行的圆出现交替错位:

  • 朝东行与朝西行之间:上一行圆的顶部(y+20)和下一行圆的底部(y+50-20=y+30)间距仅10,视觉上紧凑。
  • 朝西行与朝东行之间:上一行圆的顶部(y+50)和下一行圆的底部(y+100)间距达50,视觉上出现明显额外间隙。

解决方法

用turtle.dot()函数替代circle()即可彻底解决问题,因为dot()直接在海龟当前位置绘制实心圆,圆心与海龟位置完全重合,不受朝向影响。同时可以简化相关逻辑,因为dot()默认就是实心的,无需手动调用填充方法。

修改后的代码如下:

from turtle import Turtle, Screen
import random

colour_list = [(198, 12, 32), (250, 237, 17), (39, 76, 189), (38, 217, 68), (238, 227, 5), (229, 159, 46), (27, 40, 157), (215, 74, 12), (15, 154, 16), (199, 14, 10), (242, 246, 252), (243, 33, 165), (229, 17, 121), (73, 9, 31), (60, 14, 8), (224, 141, 211), (10, 97, 61), (221, 160, 9), (17, 18, 43), (46, 214, 232), (11, 227, 239), (81, 73, 214), (238, 156, 220), (74, 213, 167), (77, 234, 202), (52, 234, 243), (3, 67, 40)]

screen = Screen()
screen.colormode(255)
tim = Turtle()
tim.speed('fastest')
tim.penup()  # 初始抬笔,避免多余线条
column = 0

def draw_dot():
    tim.color(random.choice(colour_list))
    tim.dot(20)  # dot参数是直径,对应原circle(10)的大小

def ten_dots():
    for _ in range(9):
        draw_dot()
        tim.forward(50)
    draw_dot()  # 直接绘制第10个点,简化逻辑

def change_direction():
    if tim.heading() == 0.0:
        tim.setheading(90.0)
        tim.forward(50.0)
        tim.setheading(180.0)
    elif tim.heading() == 180.0:
        tim.setheading(90.0)
        tim.forward(50.0)
        tim.setheading(0.0)

# 初始位置调整,让点阵居中显示(可选优化)
tim.setposition(-225, -225)

while column < 10:
    ten_dots()
    if column < 9:  # 最后一行无需换行
        change_direction()
    column += 1

screen.exitonclick()

额外优化说明

  1. 移除begin_fill()和end_fill():dot()默认绘制实心圆点,无需额外填充操作。
  2. 简化ten_dots()逻辑:直接在循环外绘制第10个点,避免在方向切换函数中混合绘制与移动逻辑。
  3. 初始抬笔:避免海龟移动时画出多余线条。
  4. 初始位置调整:将海龟移到屏幕左下角,让整个点阵居中显示。
  5. 最后一行跳过换行:避免绘制完成后海龟额外向上移动。

内容的提问来源于stack exchange,提问作者Zanadukhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:25:15