Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

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

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...