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

查看:138
本文介绍了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.此参数的意思是:只运行mainloop几秒钟.因此,您可以做的是创建一个生成器,该生成器运行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天全站免登陆