pygame.event.get() 在线程内不返回任何事件 [英] pygame.event.get() not returning any events when inside a thread

查看:102
本文介绍了pygame.event.get() 在线程内不返回任何事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这段代码来处理吃豆人风格游戏的用户输入.

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.

仅供参考,我想在这里使用一个线程来最小化 pygame 未注册按键的次数(我假设这是由于主循环中的其他事情).

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).

提前致谢.

推荐答案

你根本没有得到任何事件,因为你必须在主线程中获取事件.
请参阅pygame.event 的文档:

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.

这篇关于pygame.event.get() 在线程内不返回任何事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆