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.
虽然可以从其他执行绪发送事件,但事件伫列必须在主执行绪中处理。因此,解决方案是将 event.get() 呼叫移动到主执行绪中。
以上是为什么 pygame.event.get() 在线程中执行时不返回事件?的详细内容。更多信息请关注PHP中文网其他相关文章!