在Pygame中停止多个键盘输入

时间:2019-12-12 16:07:02

标签: python pygame

我有一些使用pygame窗口来确定按下哪个键的python代码。当按下某个键时,代码会跳开并执行操作,然后再返回以查看下一个按下的键可能是什么。

我遇到的问题是,即使用户反复按下某个键,即使“代码停止运行”,pygame似乎也会记住所按下的内容,而不是等待下一次按键。我想要的是代码在完成“执行并执行操作”操作时忽略任何按键,一旦完成,就获得下一个按键。希望这有道理!

import pygame
import time

pygame.init()

screen = pygame.display.set_mode((450,282))
screen.fill((0,0,0))
pygame.display.flip()
clock = pygame.time.Clock()
done = False

def go_and_do_things():
    print("doing things")
    time.sleep(2)
    print("things done")

# Loop as long as done == False
while not done:    
    for event in pygame.event.get():  # User did something
        if event.type == pygame.KEYDOWN:
            keypressedcode = event.key # This is the ASCII code
            print("keypressedcode is " + str(keypressedcode))
            go_and_do_things()


        elif event.type == pygame.QUIT:  # If user clicked close
            done = True  # Flag that we are done so we exit this loop

    clock.tick(60)

time.sleep(4)
pygame.quit()

2 个答案:

答案 0 :(得分:1)

您可以使用pygame.event.clear。如下所述,它将在go_and_do_things()期间丢弃所有按键。

while not done:    
    for event in pygame.event.get():  # User did something

         # Any key down
        if event.type == pygame.KEYDOWN:

            keypressedcode = event.key # This is the ASCII code
            print("keypressedcode is " + str(keypressedcode))

            go_and_do_things()
            pygame.event.clear(eventtype=[pygame.KEYDOWN,
                                          pygame.KEYUP)


        elif event.type == pygame.QUIT:  # If user clicked close
            done = True  # Flag that we are done so we exit this loop

    clock.tick(60)

答案 1 :(得分:0)

  

这是一个非常简单的问题,您只需要添加另一个   keyup的event.type。您还需要添加一个变量以使其停止   运行,我将其标记为stopV if event.type == pygame.KEYUP: stopV = True,这可以让您在需要时立即将其停止。编辑,因为我想改写这个词:

重新执行此操作以使其更加清晰。

import pygame
import time

pygame.init()

screen = pygame.display.set_mode((450,282))
screen.fill((0,0,0))
pygame.display.flip()
clock = pygame.time.Clock()
done = False
unClick = False
def go_and_do_things():
     if unClick == False
         print("hello")
         # do anything you want in the function here
     else
         return
while not done:    
    for event in pygame.event.get():  # User did something

         # Any key down
        if event.type == pygame.KEYDOWN:

            keypressedcode = event.key # This is the ASCII code

            print("keypressedcode is " + str(keypressedcode))

            go_and_do_things()

        if event.type == pygame.KEYUP:

            unClick == True
        elif event.type == pygame.QUIT:  # If user clicked close
            done = True  # Flag that we are done so we exit this loop

    clock.tick(60)
相关问题