Home >Backend Development >Python Tutorial >Why is pygame.event.get() not returning events when executed within a thread?

Why is pygame.event.get() not returning events when executed within a thread?

DDD
DDDOriginal
2024-11-13 06:14:021084browse

Why is pygame.event.get() not returning events when executed within a thread?

pygame.event.get() Not Returning Events Inside Thread

Issue:

In a pac-man style game using PyGame, the receiving_inputs function is not retrieving any keyboard events when executed within a thread, while mouse events are still registered.

Code Snippet:

def receiving_inputs(self):
    while True:
        events = pg.event.get()
        for event in events:
            if event.type == pg.KEYDOWN:
                # Handle keyboard input
        time.sleep(1/60)

threading.Thread(target=self.receiving_inputs).start()

Resolution:

PyGame event handling must occur in the main thread.

According to the PyGame event documentation:

The event subsystem should be called from the main thread.

Although events can be sent from other threads, the event queue must be processed in the main thread. So the solution is to move the event.get() call into the main thread.

The above is the detailed content of Why is pygame.event.get() not returning events when executed within a thread?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn