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

Python turtle如何从指定位置开始绘图?实现从左下角到右下角画草地

解决方案

核心问题

  • turtle默认画笔初始位置为画布中心(0, 0),未主动设置初始坐标就会从中间开始绘制
  • 原有代码中position初始值为0、移动时y坐标固定为0,都是基于画布中心的坐标设定,不符合底部绘制需求

修改要点

  1. 绘图前先获取画布尺寸,计算左下角坐标,抬笔移动到该位置再开始绘制
  2. 调整position初始值为左下角x坐标,绘制过程中y坐标固定为左下角y坐标
  3. 可调整循环次数,让草地铺满整个画布底部

修复后代码

import turtle
import random

window = turtle.Screen()
bob = turtle.Turtle()
window.bgcolor("white")
window.title("TURTLE")
bob.pencolor("green")
window.colormode(255)

# 获取画布尺寸,计算左下角坐标
canvas_width = window.window_width()
canvas_height = window.window_height()
start_x = -canvas_width / 2
start_y = -canvas_height / 2

# 移动到左下角起始位置
bob.penup()
bob.goto(start_x, start_y)
bob.pendown()

position = start_x
height = 0
height11 = 0
height12 = 0
height13 = 0
height14 = 0

def draw_grass(bob):
    green = random.randint(100, 200)
    length = random.randint(10,20)
    bob.fillcolor(0,green,0)
    bob.begin_fill()
    bob.setheading(90)
    for i in range(2):
        bob.forward(length)
        bob.right(90) 
        bob.forward(3)
        bob.right(90)
    bob.end_fill()
    return length

# 循环次数设为画布宽度//3,可铺满整个底部
for i in range(canvas_width // 3):
    height = draw_grass(bob)
    position = position + 3
    bob.penup()
    bob.goto(position, start_y)
    bob.pendown()
    if height == 11 :
        height11 = height11 + 1
    elif height == 12:
        height12 = height12 + 1
    elif height == 13:
        height13 = height13 + 1

turtle.done()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:06:04