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

Pygame中鼠标点击触发显示的图片闪烁问题求助

Pygame中鼠标点击触发显示的图片闪烁问题求助

嘿,我看了你的代码和问题描述,找到导致闪烁的根源啦!

你的闪烁问题主要出在鼠标状态的处理逻辑上,再加上事件与状态获取的时机不同步,才导致图片忽显忽隐看起来闪烁。先拆解下问题:

  1. 你用pygame.mouse.get_pressed()检测左键后,只把displaybullet设为True,但这个变量一旦变成True就再也不会变回False——如果你的需求是按住左键才显示,这个逻辑完全不对;而且get_pressed()是获取当前帧的鼠标状态,操作时状态稍有波动(比如快速点击)就会出现闪烁。
  2. 你在事件循环之前就获取了鼠标状态,而pygame.event.get()会清空事件队列,这也会导致状态不同步,进一步加剧闪烁。

下面给你两种针对性的解决方案,根据你的实际需求选择:

方案1:按住左键显示,松开隐藏

把设置displaybullet的代码改成直接绑定鼠标状态,让每帧都实时更新显示状态:

# 删掉原来的 if mouse_info[0] == True: displaybullet = True
displaybullet = mouse_info[0]

修改后,只要按住左键,图片就稳定显示;松开左键就隐藏,状态完全同步,不会再出现闪烁。

方案2:点击一次显示,再点击一次隐藏

如果你的需求是通过点击切换图片的显示/隐藏状态,那就用MOUSEBUTTONDOWN事件处理,比依赖get_pressed()更可靠:

# 修改你的事件循环部分
for event in pygame.event.get():
    if event.type == QUIT:#stops the program when press exit
        pygame.quit()
        sys.exit()
    # 新增鼠标点击事件处理
    if event.type == MOUSEBUTTONDOWN:
        if event.button == 1:  # 1对应鼠标左键
            displaybullet = not displaybullet  # 切换显示状态

同时删掉原来的if mouse_info[0] == True: displaybullet = True这一行,这样每次点击左键就会切换图片的显示状态,状态稳定无闪烁。

另外给个小建议:可以把pygame.display.update()换成pygame.display.flip(),虽然大部分场景下两者效果一致,但flip()会刷新整个屏幕,偶尔能解决一些奇怪的刷新异常问题。

最后附上修改后的完整代码(以方案1为例):

import pygame, sys
from pygame.locals import *

pygame.init()

screen_size = (900, 600)#game size
screen = pygame.display.set_mode(screen_size,0, 32)
clock = pygame.time.Clock()

bullet = pygame.image.load('bullet_right.png')
display = pygame.Surface((300,200))
displaybullet = False

while True:
    display.fill((255,255,255))
    display.blit(bullet, (0,100))#no flicker :)
    
    mouse_x, mouse_y = pygame.mouse.get_pos()
    mouse_info = pygame.mouse.get_pressed()#0.lmb, 1.scroll thing 2.rmb
    
    for event in pygame.event.get():
        if event.type == QUIT:#stops the program when press exit
            pygame.quit()
            sys.exit()
    
    # 实时绑定鼠标左键状态
    displaybullet = mouse_info[0]
    
    if displaybullet:
        display.blit(bullet, (100,100))#现在不会闪烁啦:)
    
    surf = pygame.transform.scale(display, screen_size)
    screen.blit(surf, (0,0))
    pygame.display.flip()
    clock.tick(60)

备注:内容来源于stack exchange,提问作者Chaney

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 09:43:10