Pygame中的键盘输入无法正常工作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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])
答案
event.type
没有指定按下的键。这是由event.key
完成的
而不是这个:
if event.type == pygame.K_ESCAPE:
你应该做这个:
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
要么
pressed = pygame.key.get_pressed()
if pressed[pygame.K_ESCAPE]:
以上是关于Pygame中的键盘输入无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章