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

Python turtle模块绘制圆点时非首行仅输出9个而非10个的问题

问题现象

使用Python turtle模块开发彩色点阵绘图程序时,仅最下方第一行可正常绘制10个彩色圆点,其余向上排列的行均只绘制9个圆点,不符合预期。
原实现代码如下:

from turtle import Turtle, Screen
import turtle
import random
 
colours = [(232, 251, 242), (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)]
 
turtle.colormode(255)
 
dot = Turtle()
dot.color(255,255,255) # Hide turtle trail
dot.setposition(-270, -350) # Starting position
dot.pensize(21)
dot.shape("circle")
dot.speed(60)
 
ypos = dot.ycor() # Y coordinates
 
for cycle in range(1, 11): # Cycles nested forloop 10 times
 
    for num in range(1, 11): # Create 10 circles
        dot.showturtle()
        dot.color(random.choice(colours))
        dot.forward(1)
        dot.penup()
        dot.forward(50)
        dot.pendown()
 
    dot.penup()
    dot.sety((ypos + 40*cycle)) # moves turtle up one row with each iteration
    dot.setx(-270) # Sets the turtle to starting X coordinate with each iteration
 
dot.hideturtle()
 
screen = Screen()
screen.exitonclick()
问题根因

bug来自画笔状态的遗漏:

  • turtle默认初始为落笔(pendown())状态,第一行绘制时,内层循环第一次执行dot.forward(1)时画笔是落下的,配合21像素的笔宽可以正常画出第一个圆点,10次循环刚好画出10个点。
  • 每一行绘制完成后,代码主动执行了dot.penup()抬笔,再移动到下一行的起始坐标,但移动完成后没有重新落笔。
  • 进入下一行的内层循环时,第一次执行dot.forward(1)画笔处于抬起状态,无法画出圆点,直到第一次循环末尾执行dot.pendown()后,后续9次循环才能正常画点,因此除第一行外所有行都少1个圆点,仅显示9个。
修复方案

在每行起始坐标移动完成后,补充落笔操作即可。修改行循环末尾的代码段:

dot.penup()
dot.sety((ypos + 40*cycle)) # moves turtle up one row with each iteration
dot.setx(-270) # Sets the turtle to starting X coordinate with each iteration
dot.pendown() # 补充这行,移动到新行起点后落下画笔

补充优化:当前靠forward(1)蹭笔痕画圆点的逻辑容易出现画笔状态bug,更稳妥的实现是直接调用turtle内置的dot()方法直接绘制圆点,不需要频繁切换抬笔落笔状态,逻辑更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:01:07