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

Python Pillow绘制棋盘首行时颜色无法交替切换问题排查

问题原因

  • draw.rectangle()的坐标参数错误:Pillow的rectangle方法接收的坐标格式为(左上角x, 左上角y, 右下角x, 右下角y),你当前代码里第三个参数固定写死为w(也就是50),导致所有矩形的右边界都卡在x=50的位置,后续绘制的矩形要么和第一个重叠,要么宽度为0,自然看不到颜色交替效果。
  • 循环逻辑冗余不符合需求:range(0, int((image_size/5)), 10)的计算完全没有必要,200px宽度下每个格子50px,第一行只需要循环4次即可,不需要额外做i除以10的转换。

修正后代码

from PIL import Image, ImageDraw

image_size = 200

with Image.new("RGBA", (image_size, image_size)) as im:
    y = 0
    w, h = 50, 50
    red = "RED"
    blue = "BLUE"
    color = red
    draw = ImageDraw.Draw(im)
    # 按第一行的格子总数循环即可
    for col in range(4):
        # 计算当前格子的左上角x和右下角x
        x_left = col * w
        x_right = x_left + w
        draw.rectangle((x_left, y, x_right, h), fill=color)
        # 切换下一个格子的颜色
        color = blue if color == red else red
    im.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:42:01