Pygame中的键盘输入无法正常工作

时间:2018-06-10 02:35:50

标签: python python-3.x pygame

我正在尝试使用pygame和其他一些库创建虚拟合成器。可以通过两种方式播放音符:单击屏幕上的按钮或按键盘上的按键。单击屏幕时,键盘输入不起作用。

以下代码是Pygame循环,其中指定了两种输入类型。

for event in pygame.event.get():

    if event.type == pygame.QUIT:
        crashed = True

    if event.type == pygame.K_ESCAPE:
        crashed = True

    if pygame.mouse.get_pos()[0] in range(0, 50) and pygame.mouse.get_pos()[1] in range(400,
                                                                                        450) and event.type == pygame.MOUSEBUTTONDOWN:
        button(sineCod, (0, 255, 0))
        wave_1 = 0  # sine

    elif pygame.mouse.get_pos()[0] in range(100, 150) and pygame.mouse.get_pos()[1] in range(400,
                                                                                             450) and event.type == pygame.MOUSEBUTTONDOWN:
        button(sawCod, (0, 255, 0))
        wave_1 = 1  # saw
    elif pygame.mouse.get_pos()[0] in range(200, 250) and pygame.mouse.get_pos()[1] in range(400,
                                                                                             450) and event.type == pygame.MOUSEBUTTONDOWN:
        button(squareCod, (0, 255, 0))
        wave_1 = 2  # saw

    elif pygame.mouse.get_pos()[0] in range(300, 350) and pygame.mouse.get_pos()[1] in range(400,
                                                                                             450) and event.type == pygame.MOUSEBUTTONDOWN:
        button(triangleCod, (0, 255, 0))
        wave_1 = 3

    elif pygame.key.get_focused() is True:
        print("Receiving Keyboard Focus")
        if event.type == pygame.locals.KEYDOWN:
            if event.key == pygame.locals.K_w:  # C
                play(frequencies[0])

            if event.key == pygame.locals.K_2:  # C#
                play(frequencies[1])

            if event.key == pygame.K_w:  # D
                play(frequencies[2])

    if (pygame.mouse.get_pos()[0] in range(40) and pygame.mouse.get_pos()[1] in range(
            190)) or (pygame.mouse.get_pos()[0] in range(75) and pygame.mouse.get_pos()[1] in range(190,
                                                                                                    320)) and event.type == pygame.MOUSEBUTTONDOWN:  # C
        play(frequencies[0])

    elif pygame.mouse.get_pos()[0] in range(75, 150) and pygame.mouse.get_pos()[1] in range(
            320) and event.type == pygame.MOUSEBUTTONDOWN:  # D
        play(frequencies[2])

    elif pygame.mouse.get_pos()[0] in range(150, 225) and pygame.mouse.get_pos()[1] in range(
            320) and event.type == pygame.MOUSEBUTTONDOWN:  # E
        play(frequencies[4])

1 个答案:

答案 0 :(得分:0)

350px未指定按下的键。这是由<span> tag

完成的

代替此:

event.type

您应该这样做:

event.key

if event.type == pygame.K_ESCAPE: