一个线程中的 pyGame [英] pyGame in a thread

查看:23
本文介绍了一个线程中的 pyGame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 pyGame 程序作为另一个进程的一部分.使用以下代码,pyGame 似乎没有处理事件;它不响应q"键,也不绘制窗口的标题栏.如果 go() 不是作为线程运行的,它工作正常.这是在 OSX 下;我不确定这是否是问题所在.

I want to use a pyGame program as a part of another process. Using the following code, pyGame doesn't seem to be processing events; it doesn't respond to the 'q' key nor does it draw the titlebar for the window. If go() is not run as a thread, it works fine. This is under OSX; I'm unsure if that's the problem or not.

import pygame, threading, random

def go():
  pygame.init()
  surf = pygame.display.set_mode((640,480))
  pygame.fastevent.init()

  while True:
    e = pygame.fastevent.poll()
    if e.type == pygame.KEYDOWN and e.unicode == 'q':
      return

    surf.set_at((random.randint(0,640), random.randint(0,480)), (255,255,255))
    pygame.display.flip()

t = threading.Thread(target=go)
t.start()
t.join()

推荐答案

Pygame 不是线程安全的,需要 eventloop 在主线程上运行!否则,可能会出现您描述的问题.

Pygame is not threadsafe and the eventloop is required to run on the main thread! Otherwise, the problem you describe can occur.

一种解决方案是从主线程调用pygame.mainloop().

One solution is to call pygame.mainloop() from the main thread.

但是,也许您正在使用其他也需要从主线程运行的模块.在这种情况下有一个 pythonic 解决方案.您可以使用参数运行 pygame mainloop.这个参数的意思是:只运行主循环几秒钟.因此,您可以做的是创建一个运行主循环 0.1 秒的生成器,您可以定期从主线程调用该生成器.例如:

However,maybe you are using other modules that also require running from the main thread. There is in this case one pythonic solution. you have the possibility to run pygame mainloop with an argument. This argument means: run the mainloop for only a few seconds. Hence what you can do is create a generator that runs mainloop for a 0.1 second that you call periodically from main thread. For example:

def continue_pygame_loop():
    pygame.mainloop(0.1)
    yield

然后从主线程周期性地调用continue_pygame_loop()

then just call continue_pygame_loop() periodically from main thread

Tkinter 遇到同样的问题,但无法指定 runloop() 超时.对我来说,这就是为什么 pygame 很棒!

Tkinter suffers from the same problem, but has no way to specify runloop() with a timeout. For me, this is why pygame is great!

这篇关于一个线程中的 pyGame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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