我可以将键盘输入保存在列表中吗?

时间:2017-12-06 20:21:10

标签: python python-3.x pygame

我有一个代码,按下一个键可以再现计算机生成的声音,我关心的是,如何按照按键在列表中按下的顺序存储按键并打印出来?

以下是代码:

from array import array 
import pygame 
from pygame.mixer import Sound, get_init,  pre_init

class Note(pygame.mixer.Sound): 

def __init__(self, frequency, volume=.1): 
    self.frequency = frequency 
    Sound.__init__(self, self.build_samples()) 
    self.set_volume(volume) 

def build_samples(self): 
    period = int(round(get_init()[0] / self.frequency)) 
    samples = array("h", [0] * period) 
    amplitude = 2 ** (abs(get_init()[1]) - 1) - 1 
    for time in range(period): 
        if time < period / 2: 
            samples[time] = amplitude 
        else: 
            samples[time] = -amplitude 
    return samples  
pre_init(44100, -16, 1, 1024)
pygame.init() 
screen = pygame.display.set_mode([640, 480], 0) 

sounds = {} 
keymap = {pygame.K_p: 880, pygame.K_r: 440} 

while True:
    key_pressed=[]
    evt = pygame.event.wait() 
    if evt.type == pygame.QUIT: 
        break 
    elif evt.type == pygame.KEYDOWN: 
        if evt.key in keymap: 
            note = Note(keymap[evt.key]) 
            note.play(-1) 
            sounds[evt.key] = note
            key_pressed.append(note)
    elif evt.type == pygame.KEYUP: 
        if evt.key in sounds: 
            sounds.pop(evt.key).stop() 

1 个答案:

答案 0 :(得分:0)

这是问题!!!

while True:
    key_pressed=[]

这是解决方案:

key_pressed_list = key_pressed
print(key_pressed_list)