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

Pygame像素画编辑器开发:橡皮擦工具无法正常运行如何排查?

问题根源

你的橡皮擦逻辑本身是正确的,会把对应像素的status改为False,但画布绘制逻辑存在问题:Canvas的surface没有逐帧清空重绘,之前绘制的像素会永久保留在surface上,就算数据标记为不显示,也不会从画布上擦掉,所以看起来橡皮擦没有生效。
另外还有一个隐藏的网格错位问题:你Canvas类的grid方法使用了配置文件里固定的TILESIZE,没有使用用户输入的动态tile size,会导致网格和实际绘制的像素错位。

修复步骤

1. 重构Canvas类的绘制逻辑

修改Canvas文件代码,逐帧清空画布,按最新的画布数据重绘所有内容:

import pygame as pg
from settings import *

class Canvas:
    def __init__(self, app):
        self.app = app
        self.screen = app.screen
        self.image = pg.Surface((CANVAS_WIDTH, CANVAS_HEIGHT))
        self.rect = self.image.get_rect(center = app.screen_rect.center)

    def draw(self, canvas_data):
        # 逐帧清空画布为白色
        self.image.fill(WHITE)
        # 绘制网格,使用动态tile size
        self.grid()
        # 按最新数据绘制所有像素
        self.draw_pixel(canvas_data)
        # 将完整画布渲染到屏幕
        self.screen.blit(self.image, self.rect)

    def grid(self):
        tile_size = self.app.tile_size
        for x in range(0, CANVAS_WIDTH, tile_size):
            pg.draw.line(self.image, LIGHTGREY, (x, 0), (x, self.rect.bottom))
        for y in range(0, CANVAS_HEIGHT, tile_size):
            pg.draw.line(self.image, LIGHTGREY, (0, y), (self.rect.right, y))

    def draw_pixel(self, canvas_data):
        tile_size = self.app.tile_size
        for row, data in enumerate(canvas_data):
            for col, px in enumerate(data):
                if px["status"]:
                    pg.draw.rect(self.image, px["color"], pg.Rect(row * tile_size, col * tile_size, tile_size, tile_size))

2. 修改主文件的绘制调用

修改主文件draw方法里的Canvas调用部分:

def draw(self):
    self.screen.fill(SCREEN_COLOR)
    # 传入画布数据直接调用canvas的draw方法即可
    self.canvas.draw(self.canvas_grid)
    self.gui.draw()
    self.tool_buttons.update()
    self.tool_buttons.draw(self.screen)
    pg.display.flip()

这样修改后,每次渲染都会根据最新的canvas_grid生成完整画布,橡皮擦标记为不显示的像素就不会再被绘制,自然实现了擦除效果,同时也修复了网格错位的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:36:03