1

我知道已经发布了一些关于同一问题的问题,但提出的解决方案对我没有帮助。

我想在任何给定时间监视箭头键的状态(按下/未按下),所以我有以下代码:

import pygame

pygame.init()
a=[0,0,0,0]

while True:
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        a[0]=1;
    else:
        a[0]=0;
    if keys[pygame.K_RIGHT]:
        a[1]=1;
    else:
        a[1]=0;

    if keys[pygame.K_UP]:
        a[2]=1;
    else:
        a[2]=0;

    if keys[pygame.K_DOWN]:
        a[3]=1;
    else:
        a[3]=0;

    print a
    pygame.event.pump()

所以,基本上,我一直打印一个包含 4 个数字的列表每个数字代表一个箭头键(如果按下则为 1,否则为 0)。

但是,即使我长时间按住箭头键,列表的所有值也始终为零。

我还尝试打印整个数组:结果所有条目再次为零,无论我按下哪个键以及按下多长时间

任何帮助将不胜感激...

谢谢 !

编辑:忘了提到我在 Windows 7 上使用 python 2.7

4

1 回答 1

2

First off, if you haven't actually created a pygame window, no events will be passed to pygame and therefore the result of pygame.key.get_pressed() won't update. Pygame only receives events on the currrent pygame window. You're probably looking at the console, which is not receiving events. I added pygame.display.set_mode((100,100)) just after pygame.init() and then ran the program. I clicked inside the pygame window. Then the console start displaying the appropriate ones in the console.

Also suggest adding something to pause the loop like time.sleep and something like event checking to break out of it. (proper exiting)

于 2013-08-27T13:33:44.587 回答