首页 > 解决方案 > Python在线程中加载动画给出分段错误

问题描述

这是我创建的代码,用于使用 pyglet.resource.animation() 函数在后台加载动画,而应用程序执行其他一些操作。

import pyglet
import threading

animations = dict()

class LoadingThread(object):
    def __init__(self):
        thread = threading.Thread(target=self.run, args=())
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        loadAnimations()
        print("Loaded all animations.")


def loadAnimations():
    global animations
    print("In loadAnimations")
    for animation in os.listdir(os.getcwd()):
        if animation.endswith(".gif"):
            print(animation)
            #Gives segmentation fault here
            animations[animation] = pyglet.resource.animation(animation)
    print("Loaded animations")

thread = LoadingThread()

在没有线程的情况下正常调用时运行良好。如果有任何其他方法可以处理在pyglet中在后台加载动画,请提出建议。

谢谢。

标签: pythonsegmentation-faultpython-multithreadingpyglet

解决方案


正如@Frank Merrow 所建议的那样。这里的问题是我也在我的主线程中使用了函数 pyglet.resource.animation("filename.gif")函数。所以它造成了分段错误。我发现了另一个可以加载动画的功能。

pyglet.image.load_animation("filename.gif")

使用它解决了我的问题。

这个问题也可以通过启动两个线程同步运行主流程和后台工作来解决。


推荐阅读