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

使用Python Pillow绘制随机方格拼布时持续报语法错误求助

问题排查及修正

存在的问题

  • 语法层面:draw_patches调用行缺少两个闭合括号,int()转换和函数调用本身均未正确闭合,触发语法错误
  • 依赖问题:未导入PIL.Image、PIL.ImageDraw和random模块,随机函数名写错,正确为random.randint
  • 变量问题:调用draw_patches时传入的top_x、top_y等变量未定义,应使用外层循环计算的大网格边界坐标;range不支持浮点步长,grid_size计算需用整数除法//
  • 逻辑问题:lower_y计算逻辑错误,写成了higher_y - grid_size导致出现负坐标;draw_quilt内部的width、height、img是局部变量,主函数无法访问,无需在主函数重复创建图片对象

修正后可运行代码

from PIL import Image, ImageDraw
import random

def draw_quilt():
    width = 400
    height = 400
    grid_size = width // 4

    img = Image.new("RGB", (width, height))
    draw = ImageDraw.Draw(img)

    r = 0; g = 192; b = 192
    for higher_y in range(0, height, grid_size):
        lower_y = higher_y + grid_size
        r += 10; g -= 10; b -= 10 
        for higher_x in range(0, width, grid_size):
            lower_x = higher_x + grid_size
            patch_width = int(grid_size / random.randint(1,3))
            draw_patches(draw, patch_width, higher_x, higher_y, lower_x, lower_y, (r, g, b))
    return img

def draw_patches(draw, patch_width, start_x, start_y, end_x, end_y, color):
    r = color[0]; g = color[1]; b = color[2]
    for top_y in range(start_y, end_y, patch_width):
        r += 10; g += 5; b += 3
        bottom_y = top_y + patch_width
        for top_x in range(start_x, end_x, patch_width):
            r += 10; g += 5; b += 3
            bottom_x = top_x + patch_width
            draw.rectangle((top_x, top_y, bottom_x, bottom_y), fill = (r, g, b))

if __name__ == "__main__":
    img = draw_quilt()
    img.save('question4.png')
    img.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:54:02