首页 > 解决方案 > 是否可以以编程方式运行 manim(而不是从命令行)?

问题描述

最初的问题发布在 Reddit 上(https://www.reddit.com/r/manim/comments/lw3xs7/is_it_possible_to_run_manim_programmatically_and/)。我冒昧地在这里问。

假设我想编写一个简单的 GUI 应用程序,用户可以在其中输入 LaTeX 代码,单击“动画”按钮,然后 manim 在后台渲染 mp4,最后将动画呈现给用户。

是否可以使用 manim 作为模块来实现这一点?例如,通过在先前准备好的 manim 场景中插入用户输入,然后调用类似my_scene.run(output=tempfile.mp4)? 还是我必须接受用户输入,将其写入新的 scene.py 文件并运行os.subprocess("manim", "scene.py", "MyScene", "-p")

标签: pythonmanim

解决方案


其实很简单。只需使用.render(self)要渲染的 Scene 对象的方法即可。

from manim import *

# To open the movie after render.
from manim.utils.file_ops import open_file as open_media_file 


class DemoScene(Scene):
    def construct(self, alg):
        image1 = ImageMobject(np.uint8([[63, 0, 0, 0],
                                        [0, 127, 0, 0],
                                        [0, 0, 191, 0],
                                        [0, 0, 0, 255]
                                        ]))
        image1.height = 7
        self.add(image1)
        self.wait(1)


if __name__ == '__main__':
    scene = DemoScene()
    scene.render() # That's it!
    
    # Here is the extra step if you want to also open 
    # the movie file in the default video player 
    # (there is a little different syntax to open an image)
    open_media_file(scene.renderer.file_writer.movie_file_path)


推荐阅读