pygame.event.get() not returning any events when inside a thread

青春壹個敷衍的年華 提交于 2021-01-29 22:53:46

问题


So I have this code that looks after the user inputs for a pac-man style game.

def receiving_inputs(self):
    while True:
        events = pg.event.get()
        for event in events:
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_UP:
                    self.move = 'n'
                elif event.key == pg.K_RIGHT:
                    self.move = 'e'
                elif event.key == pg.K_DOWN:
                    self.move = 's'
                elif event.key == pg.K_LEFT:
                    self.move = 'w'
        time.sleep(1/60)

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

When I press any keys on my keyboard I do not get any events, however, moving the mouse around will return an event using this code.

The annoying thing is that this exact code works perfectly when not in a thread. i.e when in the program's main loop.

Just fyi I want to use a thread here to minimize the number of times pygame doesn't register a key press (which I'm assuming is due to other things in the mainloop).

Thanks in advance.


回答1:


You don't get any events at all, because you have to get the events in the main thread.
See the documentation of pygame.event:

[...] The event subsystem should be called from the main thread.

It is only possible to post events from other thread, but the event queue has to be handled in the main thread.



来源:https://stackoverflow.com/questions/56717184/pygame-event-get-not-returning-any-events-when-inside-a-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!