python - 按下按键时做一些事情 | Python

标签 python pygame keydown keyup onkeypress

只要按住某个键,我就想显示图像。如果不再按下该键 (KEYUP),图像就会消失。

在我的代码中,当我按住按键时图像会出现,但我不会立即消失。任何人都知道为什么只要我按住按键,图像就不会保持可见=?

button_pressed = False
for event in pygame.event.get():
    if event.type == KEYDOWN:               
        if event.key == K_UP:
            button_pressed = True
            print"True"

    if event.type == KEYUP:
        if event.key == K_UP:
            button_pressed = False

if button_pressed:
    DISPLAYSURF.blit(arrow_left, (20, SCREEN_HEIGHT/2 - 28))

提前致谢!!

最佳答案

一旦您将图像 block 传送到屏幕上,它就会一直留在那里,直到您在其上绘制内容。它不会自行消失。

一个简单的解决方案是在主循环的每次迭代中清除屏幕,例如像这样:

while running:
    DISPLAYSURF.fill((0, 0, 0)) # fill screen black

    for event in pygame.event.get():
        # handle events
        pass

    # I'm using 'key.get_pressed' here because using the KEYDOWN/KEYUP event
    # and a variable to track if a key is pressed totally sucks and people 
    # should stop doing this :-)
    keys = pygame.key.get_pressed() 
    if keys[pygame.K_UP]:
        # only draw image if K_UP is pressed.
        DISPLAYSURF.blit(arrow_left, (20, SCREEN_HEIGHT/2 - 28))

    pygame.display.flip()

关于python - 按下按键时做一些事情 | Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18788291/

相关文章:

python - 根据另一个文件中的行号从一个文件中提取行

python - OpenCV:自适应阈值错误(错误 -215)

python - 如何跨一维 numpy 数组中的元素获取众数

python - 两个 Pygame Sprite 的 "Bullets"镜头组合成一条长线

python - Pygame 显示卡尔曼滤波器

python - 将大型 CSV 文件加载到 Oracle 表的技术选择

python - pygame:检测操纵杆断开连接,并等待它重新连接

VB.NET 文本框 KeyDown 事件未触发

c# - 识别 KeyDown 中的菜单键

C#按键; Label 中的显示键