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

如何清除Pygame中拖动绘制时残留的预览矩形?

Pygame绘图工具矩形预览残留问题修复方案

问题说明

用Pygame制作的绘图工具,按下鼠标确定矩形起点,拖动时显示预览,松开完成绘制,但拖动过程中之前的预览矩形会残留,无法更新成当前拖动的矩形。

修复方法

核心思路是每次循环刷新背景+重绘已完成图形,避免旧预览残留:

  • 用列表保存所有已绘制完成的矩形数据
  • 主循环每帧先填充背景清除上一帧内容
  • 先重绘所有已完成的矩形,再绘制当前的预览矩形(仅拖动时)
  • 鼠标松开后,将最终矩形加入已完成列表

修改后的完整代码

import pygame 
pygame.init()

HEIGHT = 700
WIDTH = 1000

WHITE  = (255, 255, 255)
BLACK  = (0, 0, 0) 

window = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("Illustrator")

# 保存已完成绘制的矩形,每个元素是(x, y, width, height)
drawn_rects = []

def draw_rect(window, x, y, width, height, color=BLACK): 
    pygame.draw.rect(window, color, pygame.Rect(x, y, width, height))

def main():
    run = True
    mouse_button_down = False
    start_pos = None  # 保存鼠标按下时的起点

    while run:
        # 每帧先填充背景,清除上一帧内容
        window.fill(WHITE)
        # 重绘所有已完成的矩形
        for rect in drawn_rects:
            draw_rect(window, *rect)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                
            if event.type == pygame.MOUSEBUTTONDOWN:
                start_pos = pygame.mouse.get_pos()
                mouse_button_down = True
                
            if event.type == pygame.MOUSEBUTTONUP:
                if start_pos:
                    end_pos = pygame.mouse.get_pos()
                    # 计算矩形的正确坐标和尺寸(处理从右下往左上拖动的情况)
                    x = min(start_pos[0], end_pos[0])
                    y = min(start_pos[1], end_pos[1])
                    width = abs(end_pos[0] - start_pos[0])
                    height = abs(end_pos[1] - start_pos[1])
                    drawn_rects.append((x, y, width, height))
                mouse_button_down = False
                start_pos = None

        # 拖动过程中绘制预览矩形
        if mouse_button_down and start_pos:
            current_pos = pygame.mouse.get_pos()
            x = min(start_pos[0], current_pos[0])
            y = min(start_pos[1], current_pos[1])
            width = abs(current_pos[0] - start_pos[0])
            height = abs(current_pos[1] - start_pos[1])
            draw_rect(window, x, y, width, height)

        pygame.display.flip()

    pygame.quit()

if __name__ == "__main__":
    main()

额外优化点

  • 修复了原代码中从右下往左上拖动时矩形反向的问题(通过取坐标最小值和绝对值计算尺寸)
  • 移除了无用的random导入
  • 简化了鼠标状态变量,逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:27:28