Why wont the MOD_SHIFT event key work in PYGAME Mac

Viewed 83

I'm trying to build a little python program using pygame that detects when the shift key is pressed but it isn't working it isn't printing the debug print that I put in there here is my code

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"
1 Answers

Instead of using if event.key == pygame.KMOD_SHIFT: try using:

if event.mod & pygame.KMOD_SHIFT:

The documentation explains it pretty well here: 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 ==).

Basically, the & operator checks that pygame.KMOD_SHIFT was the button clicked.

Final code would look like:

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"
Related