【问题标题】:How to run pygame in background from ipython / python interpreter?如何从 ipython / python 解释器在后台运行 pygame?
【发布时间】:2022-06-17 08:53:59
【问题描述】:

我想在后台线程中从 ipython 设置一个 pygame 应用程序。

在将它导入其他任何地方之前,我已经尝试从该线程导入 pygame。

问题是当我在这个线程中启动我的主循环时,它很快就会被冻结,直到我在解释器中按下回车键。

我怎样才能让它一直运行?

注意:当启动一个只打印东西的虚拟线程时,它不会被阻塞,所以我认为它与 pygame 比与 ipython 或 python 解释器更相关。相同的行为出现在 IPython 和常规 python 解释器中

【问题讨论】:

    标签: multithreading pygame freeze pythoninterpreter


    【解决方案1】:

    我刚刚为自己的项目构建了一个这样的示例!

    我不确定是什么导致你的冻结,但我知道操作系统一直试图强制它关闭,直到我开始实际处理事件队列中的事件 - 显然当队列填满时,操作系统认为我的线断了。

    这是下面的基本思想,尽管您可以找到我的稍微详细一点的示例,其中包含更多 cmets 和示例实例供使用,Here on GitHub

    import threading
    import pygame
    
    
    class ThreadedRenderer(threading.Thread):
    
        def __init__(self, instances=[], size=(128, 128), fps=30, event_functions={}):
    
            threading.Thread.__init__(self) # Run the Thread parent init
    
            # Set up program structure
            self.instances = instances
            self.fps = fps
            self.background = background
            self.events = event_functions
            self.running = True
    
            # Set up Pygame
            pygame.init()
            self.screen = pygame.display.set_mode(size)
            self.clock = pygame.time.Clock()
    
            # Start the thread, which starts the loop
            self.start()
    
        def _step(self):
            """ Update the program objects, called each frame."""
            for inst in self.instances:
                inst.update()
    
        def _draw(self):
            """ Redraw the screen, called each frame."""
            self.screen.fill((0, 0, 0))
            for inst in self.instances:
                inst.draw(self.screen)
            pygame.display.flip()
    
        def run(self):
            """ The function that is Threaded. DO NOT call this function."""
            while self.running is True:
                self.clock.tick(self.fps)
                for event in pygame.event.get():
                    if event.type in self.events:
                        self.events[event.type](event)
                    elif event.type == pygame.QUIT: # May be overridden
                        self.running = False
                self._step()
                self._draw()
            # Below will be executed whenever the thread quits gracefully or kill is called
            pygame.quit()
            ThreadedRenderer.instantiated = False
    
        def kill(self):
            self.running = False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 2012-05-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 2014-03-23
      相关资源
      最近更新 更多