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

Python Turtle绘图中圆点与矩形块的水平对齐问题

Turtle圆点与矩形水平对齐修复

问题

使用turtle绘制圆点和矩形时,矩形块会略高于圆点,无法保持同一水平线对齐。原代码如下:

from turtle import Turtle, Screen

tim = Turtle()

def encoding_dot():
    tim.hideturtle()
    tim.dot(10)  # Draw dot without pendown()
    tim.penup()

def draw_block():
    brick_length = 30
    brick_width = 15
    tim.fillcolor('black')
    tim.begin_fill()

    for _ in range(2):
        tim.forward(brick_length)
        tim.left(90)
        tim.forward(brick_width)
        tim.left(90)

    tim.end_fill()
    tim.penup()

encoding_dot()
tim.forward(15)
draw_block()

screen = Screen()
screen.exitonclick()

原因

  • tim.dot() 是以海龟当前位置为中心绘制图形
  • 矩形绘制时,海龟的起始位置是矩形的左下角顶点,因此矩形的垂直中心比圆点中心高出 brick_width/2(即7.5像素),导致视觉上矩形偏高

解决方案

在绘制矩形前,将海龟向下移动矩形宽度的一半,让两者的垂直中心对齐。修改后的完整代码:

from turtle import Turtle, Screen

tim = Turtle()

def encoding_dot():
    tim.hideturtle()
    tim.dot(10)  # Draw dot without pendown()
    tim.penup()

def draw_block():
    brick_length = 30
    brick_width = 15
    tim.fillcolor('black')
    tim.begin_fill()

    for _ in range(2):
        tim.forward(brick_length)
        tim.left(90)
        tim.forward(brick_width)
        tim.left(90)

    tim.end_fill()
    tim.penup()

encoding_dot()
tim.forward(15)
# 调整y坐标,让矩形中心与圆点中心对齐
tim.sety(tim.ycor() - 15 / 2)
draw_block()

screen = Screen()
screen.exitonclick()

如果希望draw_block函数保持独立性(不依赖外部位置调整),可以在函数内部临时调整位置:

def draw_block():
    brick_length = 30
    brick_width = 15
    # 记录原始y坐标,临时下移
    original_y = tim.ycor()
    tim.sety(original_y - brick_width / 2)
    
    tim.fillcolor('black')
    tim.begin_fill()

    for _ in range(2):
        tim.forward(brick_length)
        tim.left(90)
        tim.forward(brick_width)
        tim.left(90)

    tim.end_fill()
    # 恢复原始y坐标
    tim.sety(original_y)
    tim.penup()

内容的提问来源于stack exchange,提问作者Barney De Jongh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:43:26