为什么 MOD_SHIFT 事件键在 PYGAME Mac 中不起作用

Why wont the MOD_SHIFT event key work in PYGAME Mac

我正在尝试使用 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

The modifier information is contained in the mod attribute of the pygame.KEYDOWN and pygame.KEYUP events. The mod attribute is a bitmask of all the modifier keys that were in a pressed state when the event occurred. The modifier information can be decoded using a bitwise AND (except for KMOD_NONE, which should be compared using 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"