【问题标题】:Python Pygame print keystroke spams the outputPython Pygame打印击键垃圾邮件输出
【发布时间】:2020-12-19 01:13:41
【问题描述】:

我一直在关注 Pygame 教程于 2019 年制作,因此可能已过时。 它应该检测箭头键并打印它,但是当我按下任何箭头键时,它会不断向打印右箭头或左箭头发送垃圾邮件并释放击键。 代码是过时的还是我的代码有错误? 而且在它开始发送垃圾邮件之前,它在 pycharm 上显示“ALSA lib pcm.c:8526:(snd_pcm_recover) underrun occurred”作为错误。 它适用于所有其他部分。

如果你需要视频链接 (https://youtu.be/FfWpgLFMI7w?t=2458)

我在 pycharm 3.8.5 上使用 pygame 2.0.0,如果它在 pycharm 和 python 上相同的话。 Linux ubuntu 20.04.1

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_LEFT:
        print("Left arrow")
    if event.key == pygame.K_RIGHT:
        print("Right arrow")
if event.type == pygame.KEYUP:
    if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
        print("Keystroke released")

谢谢

【问题讨论】:

  • 您是否使用pygame.key.set_repeat(…) 来启用重复按键事件?
  • 我检查过,我没有使用 pygame.key.set_repeat(...)。

标签: ubuntu pygame pycharm python-3.8


【解决方案1】:

我真的不明白为什么它不起作用,我尝试重写代码并且我没有错误,试试我写的:

import pygame

pygame.init()
pygame.display.set_mode((700, 700))
running = True

# initializing main loop
while running:
  # initializing event loop
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                print("Left arrow")
            if event.key == pygame.K_RIGHT:
                print("Right arrow")
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                print("Keystroke released")
        
     # lines in order to close up the window properly
        if event.type == pygame.QUIT: 
            running = False

pygame.quit()

希望它对你有用,再见。

【讨论】:

  • 现在很好用。我只需要将“if event.type == pygame.QUIT: running = False”移动到循环的末尾。非常感谢!