Can't access event.state or event.gain of ACTIVEEVENT

Question:

I was writing a paused screen for my game, the paused screen will be activated whenever the pygame window loses focus, here is my code:

import pygame
from sys import exit

pygame.init()

screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
FPS = 60

while True:
    screen.fill('Black')
    clock.tick(FPS)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

        if event.type == pygame.ACTIVEEVENT:
            if event.state == 0:
                # paused screen goes here

    pygame.display.update()

from the documentation I read, the event I should check for is pygame.ACTIVEEVENT and that event has 2 attributes: event.gain and event.state. However, when I tried to access one of them, it prompts an error:

pygame 2.1.2 (SDL 2.0.18, Python 3.10.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "D:WorkDirDinosaurtest.py", line 20, in <module>
    if event.state == 0:
AttributeError: 'Event' object has no attribute 'state'

I searched up answers online but I couldn’t find any. I found a question that is somewhat related to this:

In pygame for event.type == ACTIVEEVENT, where is the documentation on what the different event.state and event.gain parameters mean?

I tried the code from the accepted answer but the bug was still there:

Traceback (most recent call last):
 File "D:WorkDirDinosaurtest.py", line 28, in <module>
   main()
 File "D:WorkDirDinosaurtest.py", line 18, in main
   if e.state & APPMOUSEFOCUS == APPMOUSEFOCUS:
AttributeError: 'Event' object has no attribute 'state'
Asked By: Bennett Nguyen

||

Answers:

If you print the ACTIVEEVENT events, e.g. print(f"Active Event {event}") you’re trying to handle, you’ll see that the first one doesn’t have gain or state. You can probably skip this event, using something like

elif event.type == pygame.ACTIVEEVENT:
    print(f"Active Event {event}")
    try:
        print(f"Event state: {event.state}")
    except AttributeError:
        pass

You should see something like:

pygame 2.1.2 (SDL 2.0.18, Python 3.9.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Active Event <Event(32768-ActiveEvent {})>
Active Event <Event(32768-ActiveEvent {'gain': 1, 'state': 1})>
Active Event <Event(32768-ActiveEvent {'gain': 1, 'state': 0})>
Active Event <Event(32768-ActiveEvent {'gain': 0, 'state': 0})>
Active Event <Event(32768-ActiveEvent {'gain': 1, 'state': 0})>
Active Event <Event(32768-ActiveEvent {'gain': 0, 'state': 0})>

However, you’re using the latest PyGame so you can use the more specific events like WINDOWFOCUSGAINED and WINDOWFOCUSLOST to toggle your paused state. Here’s a minimal example:

import pygame
 
screen = pygame.display.set_mode((480, 320))
pygame.init()

counter = 0
paused = False
run = True
clock = pygame.time.Clock()
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.WINDOWFOCUSGAINED:
            print(f"Gain Focus {event}")
            paused = False
        elif event.type == pygame.WINDOWFOCUSLOST:
            print(f"Lost Focus {event}")
            paused = True

    screen.fill(pygame.Color("grey"))
    pygame.display.update()
    clock.tick(60)  # limit to 60 FPS
    pygame.display.set_caption(f"Paused: {paused}, Counter {counter:,}")
    if not paused:
        counter += 1

pygame.quit()

The window will look like this when runninn:
enter image description here

You’ll see console output like this:

pygame 2.1.2 (SDL 2.0.18, Python 3.9.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Gain Focus <Event(32785-WindowFocusGained {'window': None})>
Lost Focus <Event(32786-WindowFocusLost {'window': None})>
Gain Focus <Event(32785-WindowFocusGained {'window': None})>
Lost Focus <Event(32786-WindowFocusLost {'window': None})>
Gain Focus <Event(32785-WindowFocusGained {'window': None})>
Answered By: import random
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.