为什么在PYGAME Mac中不能使用MOD_SHIFT事件键



我正在尝试使用pygame构建一个小python程序,它检测何时按下shift键但它不工作它不打印我放入那里的调试打印这是我的代码

while running:
screen.fill((0, 0, 0))
x, y = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
rectangle = "green"
if event.type == pygame.MOUSEBUTTONUP:
rectangle = "red"
if event.type == pygame.KEYDOWN:
if event.key == pygame.KMOD_SHIFT:
modshift = "down"
print("debug shift")
if event.key == pygame.KMOD_CTRL:
modctrl = "down"
if event.type == pygame.KEYUP:
if event.key == pygame.KMOD_SHIFT:
modshift = "up"

代替if event.key == pygame.KMOD_SHIFT:,尝试使用:

if event.mod & pygame.KMOD_SHIFT:

文档在这里解释得很好:https://www.pygame.org/docs/ref/key.html#key-modifiers-label

修饰符信息包含在pygame的mod属性中。KEYDOWN和pygame。按键弹起事件。mod属性是事件发生时处于按下状态的所有修饰符键的位掩码。修饰符信息可以使用按位AND来解码(KMOD_NONE除外,它应该使用equals ==进行比较)。

基本上,&操作员检查pygame.KMOD_SHIFT是按下的按钮。

最终代码看起来像:

while running:
screen.fill((0, 0, 0))
x, y = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
rectangle = "green"
if event.type == pygame.MOUSEBUTTONUP:
rectangle = "red"
if event.type == pygame.KEYDOWN:
if event.mod & pygame.KMOD_SHIFT:
modshift = "down"
print("debug shift")
if event.mod & pygame.KMOD_CTRL:
modctrl = "down"
if event.type == pygame.KEYUP:
if event.mod & pygame.KMOD_SHIFT:
modshift = "up"

最新更新