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

如何在Pygame Zero中为指定位置的单个像素上色(无需使用图片)

在Pygame Zero中绘制单个像素的正确方法

你的代码没法运行主要有两个问题:

  1. 语法错误:screen.fill((50,50)color = green) 写法完全错误,既缺少逗号分隔参数,也搞反了fill方法的参数顺序
  2. API理解错误:screen.fill是用来填充矩形区域的,不是专门绘制单个像素的API——虽然可以用它填充1x1的矩形实现单像素效果,但你的参数写法完全不符合要求

两种实现单个像素上色的方法

方法1:用draw.rect绘制1x1的矩形

这是最直接的Pygame Zero原生方法,单个像素本质就是宽和高都为1的矩形:

import pgzrun
HEIGHT = 100
WIDTH = 100
red = (255, 0, 0)
yellow = (255, 255, 0)
white = (255, 255, 255)
teal = (0, 255, 255)
blue = (0, 0, 255)
green = (0, 255, 0)
magenta = (255, 0, 255)
black = (0, 0, 0)

def draw():
    screen.clear()
    screen.fill(white)
    # 绘制坐标(50,50)处的1x1绿色矩形(即单个像素)
    draw.rect(screen, green, (50, 50, 1, 1))

pgzrun.go()

方法2:操作底层Pygame Surface

Pygame Zero的screen对象封装了底层的Pygame Surface,你可以直接调用set_at方法设置单个像素:

import pgzrun
HEIGHT = 100
WIDTH = 100
red = (255, 0, 0)
yellow = (255, 255, 0)
white = (255, 255, 255)
teal = (0, 255, 255)
blue = (0, 0, 255)
green = (0, 255, 0)
magenta = (255, 0, 255)
black = (0, 0, 0)

def draw():
    screen.clear()
    screen.fill(white)
    # 获取底层Surface对象
    surface = screen.surface
    # 设置(50,50)位置的像素为绿色
    surface.set_at((50, 50), green)

pgzrun.go()

补充说明

如果想制作精灵表的替代方案,比如生成自定义图形,可以用这两种方法循环绘制多个像素,或者结合draw模块的其他API(比如draw.circle、draw.line)组合出需要的图形。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:42:56