Python Pygame 打印按键垃圾输出

Python Pygame print keystroke spams the output

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

视频link如果你需要(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")

谢谢

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

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()

希望对你有用,再见。