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

Python使用PIL生成100张100x100随机像素图时全部输出相同如何解决

需要修改的内容如下:
  • 修正变量名错误:代码中定义的尺寸变量是大写Height、Width,但循环中错误使用了小写的height、width,还存在拼写错误的heigth,首先要统一变量命名避免运行报错。
  • 每次生成新图前重置画布:当前所有图片共用同一个source_img对象,绘制完第一张后后续操作都在已画好的图上叠加,且内层循环变量首次运行完就变为0,后续99次生成不会进入绘图逻辑,直接复用了第一张的内容。需要在每次生成新图时重新加载原始底图、重置绘图对象和尺寸循环变量。
  • 修正矩形绘制的坐标逻辑:draw.rectangle的坐标参数为(x1,y1,x2,y2),原代码坐标参数写反,会导致绘制效果不符合预期。

修改后的完整代码:

from PIL import Image, ImageDraw
import random

Height = 100
Width = 100
R = 0
G = 0
B = 0

piece = 0
while piece < 100:
    # 每次生成新图都重新加载原始底图,重置画布
    source_img = Image.open("base.png").convert("RGBA")
    draw = ImageDraw.Draw(source_img)
    # 每次重置循环变量
    width = Width
    height = Height
    while width > 0:
        while height > -1:
            color = random.randint(1,3)
            if color == 1:
                R = 255
                G = 0
                B = 0
            elif color == 2:
                R = 0
                G = 255
                B = 0
            elif color == 3:
                R = 0
                G = 0
                B = 255
            draw.rectangle(((height, 0), (height, width)), fill=(R, G, B))
            height -= 1
        width -= 1
        height = Height
    piece += 1
    source_img.save("images/" + str(piece) + ".png", "PNG")
    
print("Images is done!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:45:06