API 参考:文本与公式(text)

共 14 个类,按字母排序。每个类含中文说明、继承链、参数表与上手示例,API 文档由 autodoc 从 manim v0.21.0 源码自动生成;带完整中文精讲的类见 API 索引。

BulletedList

项目符号列表:字符串数组一键排成带圆点的竖排列表,演示文稿风。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "SVGMobject"; "SVGMobject" -> "SingleStringMathTex"; "SingleStringMathTex" -> "MathTex"; "MathTex" -> "Tex"; "Tex" -> "BulletedList"; }

参数

buff

0.5,float

dot_scale_factor

2,float

tex_environment

None,str | None

dot_buff

0.1,float

快速上手

bl = BulletedList("第一项", "第二项", "第三项")

API 文档

class manim.BulletedList(*items: str, buff: float = 0.5, dot_scale_factor: float = 2, tex_environment: str | None = None, dot_buff: float = 0.1, **kwargs: Any)

基类:Tex

A bulleted list.

Parameters

items

The text elements.

buff

The vertical spacing between the list elements.

dot_scale_factor

The scale factor for the bullets.

tex_environment

The tex environment used for the text elements.

dot_buff

The horizontal spacing between the dots and the text elements.

Examples

class BulletedListExample(Scene):
    def construct(self):
        blist = BulletedList("Item 1", "Item 2", "Item 3", height=2, width=2)
        blist.set_color_by_tex("Item 1", RED)
        blist.set_color_by_tex("Item 2", GREEN)
        blist.set_color_by_tex("Item 3", BLUE)
        self.add(blist)

Code

代码高亮块:从文件或字符串渲染带语法着色的代码段,主题、字体、行号可调。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "Code"; }

参数

code_file

None,StrPath | None

code_string

None,str | None

language

None,str | None

formatter_style

'vim',str | type[Style]

tab_width

4,int

add_line_numbers

True,bool

line_numbers_from

1,int

background

'rectangle'

background_config

None,dict[str, Any] | None

paragraph_config

None,dict[str, Any] | None

快速上手

code = Code("script.py", language="python")

API 文档

class manim.Code(code_file: str | PathLike[str] | None = None, code_string: str | None = None, language: str | None = None, formatter_style: str | type[Style] = 'vim', tab_width: int = 4, add_line_numbers: bool = True, line_numbers_from: int = 1, background: Literal['rectangle', 'window'] = 'rectangle', background_config: dict[str, Any] | None = None, paragraph_config: dict[str, Any] | None = None)

基类:VMobject

A highlighted source code listing.

Examples

Normal usage:

listing = Code(
    "helloworldcpp.cpp",
    tab_width=4,
    formatter_style="emacs",
    background="window",
    language="cpp",
    background_config={"stroke_color": WHITE},
    paragraph_config={"font": "Noto Sans Mono"},
)

We can also render code passed as a string. As the automatic language detection can be a bit flaky, it is recommended to specify the language explicitly:

class CodeFromString(Scene):
    def construct(self):
        code = '''from manim import Scene, Square

class FadeInSquare(Scene):
    def construct(self):
        s = Square()
        self.play(FadeIn(s))
        self.play(s.animate.scale(2))
        self.wait()'''

        rendered_code = Code(
            code_string=code,
            language="python",
            background="window",
            background_config={"stroke_color": "maroon"},
        )
        self.add(rendered_code)

Parameters

code_file

The path to the code file to display.

code_string

Alternatively, the code string to display.

language

The programming language of the code. If not specified, it will be guessed from the file extension or the code itself.

formatter_style

The style to use for the code highlighting. This can be either the name of a Pygments style or a custom Pygments style class. Defaults to "vim". A list of all available styles can be obtained by calling Code.get_styles_list(); style classes can be retrieved with Code.get_pygments_style().

tab_width

The width of a tab character in spaces. Defaults to 4.

add_line_numbers

Whether to display line numbers. Defaults to True.

line_numbers_from

The first line number to display. Defaults to 1.

background

The type of background to use. Can be either "rectangle" (the default) or "window".

background_config

Keyword arguments passed to the background constructor. Default settings are stored in the class attribute default_background_config (which can also be modified directly). If fill_color is not specified, it is taken from the selected formatter_style.

paragraph_config

Keyword arguments passed to the constructor of the Paragraph objects holding the code, and the line numbers. Default settings are stored in the class attribute default_paragraph_config (which can also be modified directly). The color setting is ignored because colors are determined by the selected Pygments style.

Notes

备注

The Pygments style controls the colors of the rendered code, including its default foreground, background, and line number colors. To customize the color scheme, pass a custom Pygments style class via formatter_style rather than setting paragraph_config["color"]. See Creating own styles with Pygments for details.

For example, a built-in style can be subclassed without importing its style class directly:

from manim import *
from pygments.token import Comment

BaseStyle = Code.get_pygments_style("vim")


class CustomStyle(BaseStyle):
    background_color = "#1e1e1e"
    line_number_color = "#858585"
    styles = {
        **BaseStyle.styles,
        Comment: "italic #6a9955",
    }


class Example(Scene):
    def construct(self):
        rendered_code = Code(
            code_string="print('Hello, world!')  # greeting",
            language="python",
            formatter_style=CustomStyle,
        )

        self.add(rendered_code)
        self.wait(2)
classmethod get_pygments_style(name: str) → type[Style]

Return the Pygments style registered under name.

Parameters
name

The name of the Pygments style to retrieve.

Returns
type[Style]

The corresponding Pygments style class.

classmethod get_styles_list() → list[str]

Get the list of all available formatter styles.

DecimalNumber

可动小数的数字文本:set_value 即重排,配 ValueTracker 做计数器。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "DecimalNumber"; }

参数

number

0,float

num_decimal_places

2,int

mob_class

<class 'manim.mobject.text.…

include_sign

False,bool

group_with_commas

True,bool

digit_buff_per_font_unit

0.001,float

show_ellipsis

False,bool

unit

None,str | None

unit_buff_per_font_unit

0,float

include_background_rectangle

False,bool

edge_to_fix

array([-1., 0., 0.]),Vector3DLike

font_size

48,float

stroke_width

0,float

fill_opacity

1.0,float

快速上手

num = DecimalNumber(0, num_decimal_places=2)

API 文档

class manim.DecimalNumber(number: float = 0, num_decimal_places: int = 2, mob_class: type[SingleStringMathTex] = <class 'manim.mobject.text.tex_mobject.MathTex'>, include_sign: bool = False, group_with_commas: bool = True, digit_buff_per_font_unit: float = 0.001, show_ellipsis: bool = False, unit: str | None = None, unit_buff_per_font_unit: float = 0, include_background_rectangle: bool = False, edge_to_fix: float64] | tuple[float, float, float]=array([-1., 0., 0.]), font_size: float = 48, stroke_width: float = 0, fill_opacity: float = 1.0, **kwargs: Any)

基类:VMobject

An mobject representing a decimal number.

Parameters

number

The numeric value to be displayed. It can later be modified using set_value().

num_decimal_places

The number of decimal places after the decimal separator. Values are automatically rounded.

mob_class

The class for rendering digits and units, by default MathTex.

include_sign

Set to True to include a sign for positive numbers and zero.

group_with_commas

When True thousands groups are separated by commas for readability.

digit_buff_per_font_unit

Additional spacing between digits. Scales with font size.

show_ellipsis

When a number has been truncated by rounding, indicate with an ellipsis (...).

unit

A unit string which can be placed to the right of the numerical values.

unit_buff_per_font_unit

An additional spacing between the numerical values and the unit. A value of unit_buff_per_font_unit=0.003 gives a decent spacing. Scales with font size.

include_background_rectangle

Adds a background rectangle to increase contrast on busy scenes.

edge_to_fix

Assuring right- or left-alignment of the full object.

font_size

Size of the font.

Examples

class MovingSquareWithUpdaters(Scene):
    def construct(self):
        decimal = DecimalNumber(
            0,
            show_ellipsis=True,
            num_decimal_places=3,
            include_sign=True,
            unit=r"\text{M-Units}",
            unit_buff_per_font_unit=0.003
        )
        square = Square().to_edge(UP)

        decimal.add_updater(lambda d: d.next_to(square, RIGHT))
        decimal.add_updater(lambda d: d.set_value(square.get_center()[1]))
        self.add(square, decimal)
        self.play(
            square.animate.to_edge(DOWN),
            rate_func=there_and_back,
            run_time=5,
        )
        self.wait()
property font_size: float

The font size of the tex mobject.

set_value(number: float) → Self

Set the value of the DecimalNumber to a new number.

Parameters
number

The value that will overwrite the current number of the DecimalNumber.

Integer

整数版 DecimalNumber:无小数点,步进计数常用。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "DecimalNumber"; "DecimalNumber" -> "Integer"; }

参数

number

0,float

num_decimal_places

0,int

API 文档

class manim.Integer(number: float = 0, num_decimal_places: int = 0, **kwargs: Any)

基类:DecimalNumber

A class for displaying Integers.

Examples

class IntegerExample(Scene):
    def construct(self):
        self.add(Integer(number=2.5).set_color(ORANGE).scale(2.5).set_x(-0.5).set_y(0.8))
        self.add(Integer(number=3.14159, show_ellipsis=True).set_x(3).set_y(3.3).scale(3.14159))
        self.add(Integer(number=42).set_x(2.5).set_y(-2.3).set_color_by_gradient(BLUE, TEAL).scale(1.7))
        self.add(Integer(number=6.28).set_x(-1.5).set_y(-2).set_color(YELLOW).scale(1.4))

MarkupText

Pango 标记语言文本:字符串里直接写 b/i/span 等标签实现富文本混排。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "SVGMobject"; "SVGMobject" -> "MarkupText"; }

参数

text

—,str

fill_opacity

1,float

stroke_width

0,float

color

None

font_size

48,float

line_spacing

-1,float

font

'',str

slant

'NORMAL',str

weight

'NORMAL',str

justify

False,bool

gradient

None

tab_width

4,int

height

None,int | None

width

None,int | None

should_center

True,bool

disable_ligatures

False,bool

warn_missing_font

True,bool

快速上手

mt = MarkupText('<b>bold</b> <span foreground="#FFFF00">yellow</span>')

API 文档

class manim.MarkupText(text: str, fill_opacity: float = 1, stroke_width: float = 0, color: ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] | None = None, font_size: float = 48, line_spacing: float = -1, font: str = '', slant: str = 'NORMAL', weight: str = 'NORMAL', justify: bool = False, gradient: Iterable[ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float]] | None = None, tab_width: int = 4, height: int | None = None, width: int | None = None, should_center: bool = True, disable_ligatures: bool = False, warn_missing_font: bool = True, **kwargs: Any)

基类:SVGMobject

Display (non-LaTeX) text rendered using Pango.

Text objects behave like a VGroup-like iterable of all characters in the given text. In particular, slicing is possible.

**What is PangoMarkup?**

PangoMarkup is a small markup language like html and it helps you avoid using "range of characters" while coloring or styling a piece a Text. You can use this language with MarkupText.

A simple example of a marked-up string might be:

<span foreground="blue" size="x-large">Blue text</span> is <i>cool</i>!"

and it can be used with MarkupText as

class MarkupExample(Scene):
    def construct(self):
        text = MarkupText('<span foreground="blue" size="x-large">Blue text</span> is <i>cool</i>!"')
        self.add(text)

A more elaborate example would be:

class MarkupElaborateExample(Scene):
    def construct(self):
        text = MarkupText(
            '<span foreground="purple">ا</span><span foreground="red">َ</span>'
            'ل<span foreground="blue">ْ</span>ع<span foreground="red">َ</span>ر'
            '<span foreground="red">َ</span>ب<span foreground="red">ِ</span>ي'
            '<span foreground="green">ّ</span><span foreground="red">َ</span>ة'
            '<span foreground="blue">ُ</span>'
        )
        self.add(text)

PangoMarkup can also contain XML features such as numeric character entities such as &#169; for © can be used too.

The most general markup tag is <span>, then there are some convenience tags.

Here is a list of supported tags:

  • <b>bold</b>, <i>italic</i> and <b><i>bold+italic</i></b>

  • <u>underline</u> and <s>strike through</s>

  • <tt>typewriter font</tt>

  • <big>bigger font</big> and <small>smaller font</small>

  • <sup>superscript</sup> and <sub>subscript</sub>

  • <span underline="double" underline_color="green">double underline</span>

  • <span underline="error">error underline</span>

  • <span overline="single" overline_color="green">overline</span>

  • <span strikethrough="true" strikethrough_color="red">strikethrough</span>

  • <span font_family="sans">temporary change of font</span>

  • <span foreground="red">temporary change of color</span>

  • <span fgcolor="red">temporary change of color</span>

  • <gradient from="YELLOW" to="RED">temporary gradient</gradient>

For <span> markup, colors can be specified either as hex triples like #aabbcc or as named CSS colors like AliceBlue. The <gradient> tag is handled by Manim rather than Pango, and supports hex triplets or Manim constants like RED or RED_A. If you want to use Manim constants like RED_A together with <span>, you will need to use Python's f-String syntax as follows:

MarkupText(f'<span foreground="{RED_A}">here you go</span>')

If your text contains ligatures, the MarkupText class may incorrectly determine the first and last letter when creating the gradient. This is due to the fact that fl are two separate characters, but might be set as one single glyph - a ligature. If your language does not depend on ligatures, consider setting disable_ligatures to True. If you must use ligatures, the gradient tag supports an optional attribute offset which can be used to compensate for that error.

For example:

  • <gradient from="RED" to="YELLOW" offset="1">example</gradient> to start the gradient one letter earlier

  • <gradient from="RED" to="YELLOW" offset=",1">example</gradient> to end the gradient one letter earlier

  • <gradient from="RED" to="YELLOW" offset="2,1">example</gradient> to start the gradient two letters earlier and end it one letter earlier

Specifying a second offset may be necessary if the text to be colored does itself contain ligatures. The same can happen when using HTML entities for special chars.

When using underline, overline or strikethrough together with <gradient> tags, you will also need to use the offset, because underlines are additional paths in the final SVGMobject. Check out the following example.

Escaping of special characters: > should be written as &gt; whereas < and & must be written as &lt; and &amp;.

You can find more information about Pango markup formatting at the corresponding documentation page: Pango Markup. Please be aware that not all features are supported by this class and that the <gradient> tag mentioned above is not supported by Pango.

Parameters

text

The text that needs to be created as mobject.

fill_opacity

The fill opacity, with 1 meaning opaque and 0 meaning transparent.

stroke_width

Stroke width.

font_size

Font size.

line_spacing

Line spacing.

font

Global font setting for the entire text. Local overrides are possible.

slant

Global slant setting, e.g. NORMAL or ITALIC. Local overrides are possible.

weight

Global weight setting, e.g. NORMAL or BOLD. Local overrides are possible.

gradient

Global gradient setting. Local overrides are possible.

warn_missing_font

If True (default), Manim will issue a warning if the font does not exist in the (case-sensitive) list of fonts returned from manimpango.list_fonts().

Returns

MarkupText

The text displayed in form of a VGroup-like mobject.

Examples

class BasicMarkupExample(Scene):
    def construct(self):
        text1 = MarkupText("<b>foo</b> <i>bar</i> <b><i>foobar</i></b>")
        text2 = MarkupText("<s>foo</s> <u>bar</u> <big>big</big> <small>small</small>")
        text3 = MarkupText("H<sub>2</sub>O and H<sub>3</sub>O<sup>+</sup>")
        text4 = MarkupText("type <tt>help</tt> for help")
        text5 = MarkupText(
            '<span underline="double">foo</span> <span underline="error">bar</span>'
        )
        group = VGroup(text1, text2, text3, text4, text5).arrange(DOWN)
        self.add(group)
class ColorExample(Scene):
    def construct(self):
        text1 = MarkupText(
            f'all in red <span fgcolor="{YELLOW}">except this</span>', color=RED
        )
        text2 = MarkupText("nice gradient", gradient=(BLUE, GREEN))
        text3 = MarkupText(
            'nice <gradient from="RED" to="YELLOW">intermediate</gradient> gradient',
            gradient=(BLUE, GREEN),
        )
        text4 = MarkupText(
            'fl ligature <gradient from="RED" to="YELLOW">causing trouble</gradient> here'
        )
        text5 = MarkupText(
            'fl ligature <gradient from="RED" to="YELLOW" offset="1">defeated</gradient> with offset'
        )
        text6 = MarkupText(
            'fl ligature <gradient from="RED" to="YELLOW" offset="1">floating</gradient> inside'
        )
        text7 = MarkupText(
            'fl ligature <gradient from="RED" to="YELLOW" offset="1,1">floating</gradient> inside'
        )
        group = VGroup(text1, text2, text3, text4, text5, text6, text7).arrange(DOWN)
        self.add(group)
class UnderlineExample(Scene):
    def construct(self):
        text1 = MarkupText(
            '<span underline="double" underline_color="green">bla</span>'
        )
        text2 = MarkupText(
            '<span underline="single" underline_color="green">xxx</span><gradient from="#ffff00" to="RED">aabb</gradient>y'
        )
        text3 = MarkupText(
            '<span underline="single" underline_color="green">xxx</span><gradient from="#ffff00" to="RED" offset="-1">aabb</gradient>y'
        )
        text4 = MarkupText(
            '<span underline="double" underline_color="green">xxx</span><gradient from="#ffff00" to="RED">aabb</gradient>y'
        )
        text5 = MarkupText(
            '<span underline="double" underline_color="green">xxx</span><gradient from="#ffff00" to="RED" offset="-2">aabb</gradient>y'
        )
        group = VGroup(text1, text2, text3, text4, text5).arrange(DOWN)
        self.add(group)
class FontExample(Scene):
    def construct(self):
        text1 = MarkupText(
            'all in sans <span font_family="serif">except this</span>', font="sans"
        )
        text2 = MarkupText(
            '<span font_family="serif">mixing</span> <span font_family="sans">fonts</span> <span font_family="monospace">is ugly</span>'
        )
        text3 = MarkupText("special char > or &gt;")
        text4 = MarkupText("special char &lt; and &amp;")
        group = VGroup(text1, text2, text3, text4).arrange(DOWN)
        self.add(group)
class NewlineExample(Scene):
    def construct(self):
        text = MarkupText('foooo<span foreground="red">oo\nbaa</span>aar')
        self.add(text)
class NoLigaturesExample(Scene):
    def construct(self):
        text1 = MarkupText('fl<gradient from="RED" to="GREEN">oat</gradient>ing')
        text2 = MarkupText('fl<gradient from="RED" to="GREEN">oat</gradient>ing', disable_ligatures=True)
        group = VGroup(text1, text2).arrange(DOWN)
        self.add(group)

As MarkupText uses Pango to render text, rendering non-English characters is easily possible:

class MultiLanguage(Scene):
    def construct(self):
        morning = MarkupText("வணக்கம்", font="sans-serif")
        japanese = MarkupText(
            '<span fgcolor="blue">日本</span>へようこそ'
        )  # works as in ``Text``.
        mess = MarkupText("Multi-Language", weight=BOLD)
        russ = MarkupText("Здравствуйте मस नम म ", font="sans-serif")
        hin = MarkupText("नमस्ते", font="sans-serif")
        chinese = MarkupText("臂猿「黛比」帶著孩子", font="sans-serif")
        group = VGroup(morning, japanese, mess, russ, hin, chinese).arrange(DOWN)
        self.add(group)

You can justify the text by passing justify parameter.

class JustifyText(Scene):
    def construct(self):
        ipsum_text = (
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
            "Praesent feugiat metus sit amet iaculis pulvinar. Nulla posuere "
            "quam a ex aliquam, eleifend consectetur tellus viverra. Aliquam "
            "fermentum interdum justo, nec rutrum elit pretium ac. Nam quis "
            "leo pulvinar, dignissim est at, venenatis nisi."
        )
        justified_text = MarkupText(ipsum_text, justify=True).scale(0.4)
        not_justified_text = MarkupText(ipsum_text, justify=False).scale(0.4)
        just_title = Title("Justified")
        njust_title = Title("Not Justified")
        self.add(njust_title, not_justified_text)
        self.play(
            FadeOut(not_justified_text),
            FadeIn(justified_text),
            FadeOut(njust_title),
            FadeIn(just_title),
        )
        self.wait(1)

Tests

Check that the creation of MarkupText works:

>>> MarkupText('The horse does not eat cucumber salad.')
MarkupText('The horse does not eat cucumber salad.')

MathTex

LaTeX 公式文本:每个 LaTeX 片段是独立子对象,可按下标索引做局部动画,数学视频的核心。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "SVGMobject"; "SVGMobject" -> "SingleStringMathTex"; "SingleStringMathTex" -> "MathTex"; }

参数

arg_separator

' ',str

substrings_to_isolate

None,Iterable[str] | None

tex_to_color_map

None

tex_environment

'align*',str | None

快速上手

eq = MathTex(r" rac{a}{b} = \sqrt{c}")

API 文档

class manim.MathTex(*tex_strings: str, arg_separator: str = ' ', substrings_to_isolate: Iterable[str] | None = None, tex_to_color_map: dict[str, ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float]] | None = None, tex_environment: str | None = 'align*', **kwargs: Any)

基类:SingleStringMathTex

A string compiled with LaTeX in math mode.

Examples

class Formula(Scene):
    def construct(self):
        t = MathTex(r"\int_a^b f'(x) dx = f(b)- f(a)")
        self.add(t)

Notes

Double-brace notation {{ ... }} can be used to split a single string argument into multiple submobjects without having to pass separate strings:

MathTex(r"{{ a^2 }} + {{ b^2 }} = {{ c^2 }}")

Each {{ ... }} group and every piece of text between groups becomes its own submobject, which is useful for TransformMatchingTex animations.

For {{ to be recognised as a group opener it must appear either at the very start of the string or be immediately preceded by a whitespace character. {{ that follows non-whitespace — such as in \frac{{{n}}}{k} or a^{{2}} — is left untouched, so ordinary nested-brace LaTeX is not accidentally split. To prevent an unintentional split, insert a space between the two braces: {{ ... }} → { { ... } }.

Tests

Check that creating a MathTex works:

>>> MathTex('a^2 + b^2 = c^2')
MathTex('a^2 + b^2 = c^2')

Check that double brace group splitting works correctly:

>>> t1 = MathTex('{{ a }} + {{ b }} = {{ c }}')
>>> len(t1.submobjects)
5
>>> t2 = MathTex(r"\frac{1}{a+b\sqrt{2}}")
>>> len(t2.submobjects)
1
set_opacity_by_tex(tex: str, opacity: float = 0.5, remaining_opacity: float | None = None, **kwargs: Any) → Self

Sets the opacity of the tex specified. If 'remaining_opacity' is specified, then the remaining tex will be set to that opacity.

Parameters
tex

The tex to set the opacity of.

opacity

Default 0.5. The opacity to set the tex to

remaining_opacity

Default None. The opacity to set the remaining tex to. If None, then the remaining tex will not be changed

MathTypst

Typst 排版的公式对象(v0.21 新增):用 Typst 语法替代 LaTeX,需安装 typst。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "SVGMobject"; "SVGMobject" -> "Typst"; "Typst" -> "MathTypst"; }

参数

API 文档

class manim.MathTypst(math_expression: str, **kwargs: Any)

基类:Typst

Convenience wrapper: wraps the input in Typst math delimiters.

The expression is rendered as a display-level equation ($ ... $ with surrounding spaces).

Supports the {{ ... }} double-brace notation for grouping sub-expressions. Each {{ content }} is wrapped in a labeled manimgrp call so that the resulting SVG contains identifiable groups accessible via select().

Groups can optionally be given explicit labels: {{ content : label }}. Without a label, groups are auto-numbered (_grp-0, _grp-1, …).

Parameters

math_expression

Typst math-mode content without the $ ... $ delimiters. May contain {{ ... }} groups.

**kwargs

Forwarded to Typst.

Examples

class DisplayMath(Scene):
    def construct(self):
        eq = MathTypst(r"sum_(k=0)^n k = (n(n+1)) / 2")
        self.add(eq)
class GroupedMath(Scene):
    def construct(self):
        eq = MathTypst("{{ a^2 + b^2 : lhs }} = {{ c^2 }}")
        eq.select("lhs").set_color(RED) # "a^2 + b^2"
        eq.select(0).set_color(BLUE)    # "c^2" (auto-numbered: "grp-0")
        self.add(eq)

Paragraph

多段落文本块:长文字自动分行成段,排文章类内容用。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "VGroup"; "VGroup" -> "Paragraph"; }

参数

line_spacing

-1,float

alignment

None,str | None

API 文档

class manim.Paragraph(*text: str, line_spacing: float = -1, alignment: str | None = None, **kwargs: Any)

基类:VGroup

Display a paragraph of text.

For a given Paragraph par, the attribute par.chars is a VGroup containing all the lines. In this context, every line is constructed as a VGroup of characters contained in the line.

Parameters

line_spacing

Represents the spacing between lines. Defaults to -1, which means auto.

alignment

Defines the alignment of paragraph. Defaults to None. Possible values are "left", "right" or "center".

Examples

Normal usage:

paragraph = Paragraph(
    "this is a awesome",
    "paragraph",
    "With \nNewlines",
    "\tWith Tabs",
    "  With Spaces",
    "With Alignments",
    "center",
    "left",
    "right",
)

Remove unwanted invisible characters:

self.play(Transform(remove_invisible_chars(paragraph.chars[0:2]),
                    remove_invisible_chars(paragraph.chars[3][0:3]))

SingleStringMathTex

单个 LaTeX 字符串的公式对象:不做分词切片,MathTex 的底层形式。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "SVGMobject"; "SVGMobject" -> "SingleStringMathTex"; }

参数

tex_string

—,str

stroke_width

0,float

should_center

True,bool

height

None,float | None

organize_left_to_right

False,bool

tex_environment

'align*',str | None

tex_template

None,TexTemplate | None

font_size

48,float

color

None

API 文档

class manim.SingleStringMathTex(tex_string: str, stroke_width: float = 0, should_center: bool = True, height: float | None = None, organize_left_to_right: bool = False, tex_environment: str | None = 'align*', tex_template: TexTemplate | None = None, font_size: float = 48, color: ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] | None = None, **kwargs: Any)

基类:SVGMobject

Elementary building block for rendering text with LaTeX.

Tests

Check that creating a SingleStringMathTex object works:

>>> SingleStringMathTex('Test')
SingleStringMathTex('Test')
property font_size: float

The font size of the tex mobject.

init_colors(propagate_colors: bool = True) → Self

Initializes the colors.

Gets called upon creation. This is an empty method that can be implemented by subclasses.

Tex

LaTeX 完整文档模式:可加载宏包与自定义导言区,出整个 LaTeX 页面效果。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "SVGMobject"; "SVGMobject" -> "SingleStringMathTex"; "SingleStringMathTex" -> "MathTex"; "MathTex" -> "Tex"; }

参数

arg_separator

'',str

tex_environment

'center',str | None

API 文档

class manim.Tex(*tex_strings: str, arg_separator: str = '', tex_environment: str | None = 'center', **kwargs: Any)

基类:MathTex

A string compiled with LaTeX in normal mode.

The color can be set using the color argument. Any parts of the tex_string that are colored by the TeX commands \color or \textcolor will retain their original color.

Tests

Check whether writing a LaTeX string works:

>>> Tex('The horse does not eat cucumber salad.')
Tex('The horse does not eat cucumber salad.')

Text

Pango 渲染的系统字体文本:中文、emoji 原生支持,t2c/t2f 子串改色改字体,文字类内容首选。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "SVGMobject"; "SVGMobject" -> "Text"; }

参数

text

—,str

fill_opacity

1.0,float

stroke_width

0,float

color

None

font_size

48,float

line_spacing

-1,float

font

'',str

slant

'NORMAL',str

weight

'NORMAL',str

t2c

None,dict[str, str] | None

t2f

None,dict[str, str] | None

t2g

None

t2s

None,dict[str, str] | None

t2w

None,dict[str, str] | None

gradient

None

tab_width

4,int

warn_missing_font

True,bool

height

None,float | None

width

None,float | None

should_center

True,bool

disable_ligatures

False,bool

use_svg_cache

False,bool

快速上手

t = Text("你好,Manim!", t2c={"Manim": YELLOW})

API 文档

class manim.Text(text: str, fill_opacity: float = 1.0, stroke_width: float = 0, color: ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] | None = None, font_size: float = 48, line_spacing: float = -1, font: str = '', slant: str = 'NORMAL', weight: str = 'NORMAL', t2c: dict[str, str] | None = None, t2f: dict[str, str] | None = None, t2g: dict[str, Iterable[ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float]]] | None = None, t2s: dict[str, str] | None = None, t2w: dict[str, str] | None = None, gradient: Iterable[ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float]] | None = None, tab_width: int = 4, warn_missing_font: bool = True, height: float | None = None, width: float | None = None, should_center: bool = True, disable_ligatures: bool = False, use_svg_cache: bool = False, **kwargs: Any)

基类:SVGMobject

Display (non-LaTeX) text rendered using Pango.

Text objects behave like a VGroup-like iterable of all characters in the given text. In particular, slicing is possible.

警告

Whitespace and newline characters are stripped internally and never become their own submobject (there is nothing to render for them), so slicing indices are interpreted differently depending on where they are used, and the two conventions disagree with each other:

  • Slicing the object itself (my_text[3:5]) indexes into the rendered characters, i.e. the text with whitespace removed. For Text("Hello world"), index 5 refers to "w", not to the space between the two words.

  • The slice syntax in t2c/t2s/t2w/t2f/t2g (e.g. t2c={'[3:7]': RED}) indexes into the original text argument, whitespace included. For Text("Hello World"), t2c={'[3:7]': RED} colors "l", "o", "W" (the space at index 5 falls in range but has nothing to color), whereas my_text[3:7] selects the 4 rendered characters "loWo".

When the substring you want to select is known in advance, prefer keying t2c/t2s/t2w/t2f/t2g by that substring directly (e.g. t2c={"world": RED}), which matches by text search instead of by index and is unaffected by this quirk.

Parameters

text

The text that needs to be created as a mobject.

font

The font family to be used to render the text. This is either a system font or one loaded with register_font(). Note that font family names may be different across operating systems.

warn_missing_font

If True (default), Manim will issue a warning if the font does not exist in the (case-sensitive) list of fonts returned from manimpango.list_fonts().

Returns

Text

The mobject-like VGroup.

Examples

class Example1Text(Scene):
    def construct(self):
        text = Text('Hello world').scale(3)
        self.add(text)
class TextColorExample(Scene):
    def construct(self):
        text1 = Text('Hello world', color=BLUE).scale(3)
        text2 = Text('Hello world', gradient=(BLUE, GREEN)).scale(3).next_to(text1, DOWN)
        self.add(text1, text2)
class TextItalicAndBoldExample(Scene):
    def construct(self):
        text1 = Text("Hello world", slant=ITALIC)
        text2 = Text("Hello world", t2s={'world':ITALIC})
        text3 = Text("Hello world", weight=BOLD)
        text4 = Text("Hello world", t2w={'world':BOLD})
        text5 = Text("Hello world", t2c={'o':YELLOW}, disable_ligatures=True)
        text6 = Text(
            "Visit us at docs.manim.community",
            t2c={"docs.manim.community": YELLOW},
            disable_ligatures=True,
       )
        text6.scale(1.3).shift(DOWN)
        self.add(text1, text2, text3, text4, text5 , text6)
        Group(*self.mobjects).arrange(DOWN, buff=.8).set(height=config.frame_height-LARGE_BUFF)
class TextMoreCustomization(Scene):
    def construct(self):
        text1 = Text(
            'Google',
            t2c={'[:1]': '#3174f0', '[1:2]': '#e53125',
                 '[2:3]': '#fbb003', '[3:4]': '#3174f0',
                 '[4:5]': '#269a43', '[5:]': '#e53125'}, font_size=58).scale(3)
        self.add(text1)

As Text uses Pango to render text, rendering non-English characters is easily possible:

class MultipleFonts(Scene):
    def construct(self):
        morning = Text("வணக்கம்", font="sans-serif")
        japanese = Text(
            "日本へようこそ", t2c={"日本": BLUE}
        )  # works same as ``Text``.
        mess = Text("Multi-Language", weight=BOLD)
        russ = Text("Здравствуйте मस नम म ", font="sans-serif")
        hin = Text("नमस्ते", font="sans-serif")
        arb = Text(
            "صباح الخير \n تشرفت بمقابلتك", font="sans-serif"
        )  # don't mix RTL and LTR languages nothing shows up then ;-)
        chinese = Text("臂猿「黛比」帶著孩子", font="sans-serif")
        self.add(morning, japanese, mess, russ, hin, arb, chinese)
        for i,mobj in enumerate(self.mobjects):
            mobj.shift(DOWN*(i-3))
class PangoRender(Scene):
    def construct(self):
        morning = Text("வணக்கம்", font="sans-serif")
        self.play(Write(morning))
        self.wait(2)

Tests

Check that the creation of Text works:

>>> Text('The horse does not eat cucumber salad.')
Text('The horse does not eat cucumber salad.')
init_colors(propagate_colors: bool = True) → Self

Initializes the colors.

Gets called upon creation. This is an empty method that can be implemented by subclasses.

Title

居中放大加下划线的标题文本:章节标题专用。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "SVGMobject"; "SVGMobject" -> "SingleStringMathTex"; "SingleStringMathTex" -> "MathTex"; "MathTex" -> "Tex"; "Tex" -> "Title"; }

参数

include_underline

True,bool

match_underline_width_to_text

False,bool

underline_buff

0.25,float

快速上手

self.add(Title("第三章:动画进阶"))

API 文档

class manim.Title(*text_parts: str, include_underline: bool = True, match_underline_width_to_text: bool = False, underline_buff: float = 0.25, **kwargs: Any)

基类:Tex

A mobject representing an underlined title.

Examples

import manim

class TitleExample(Scene):
    def construct(self):
        banner = ManimBanner()
        title = Title(f"Manim version {manim.__version__}")
        self.add(banner, title)

Typst

Typst 文档模式文本(v0.21 新增):整个文档用 Typst 排版,类似 Tex 的定位。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "SVGMobject"; "SVGMobject" -> "Typst"; }

参数

typst_code

—,str

font_size

48,float

typst_preamble

'',str

color

None

stroke_width

None,float | None

font_paths

None,list[str | Path] | None

track_baselines

False,bool

should_center

True,bool

height

None,float | None

API 文档

class manim.Typst(typst_code: str, *, font_size: float = 48, typst_preamble: str = '', color: ManimColor | int | str | NDArray[int64] | tuple[int, int, int] | NDArray[float64] | tuple[float, float, float] | tuple[int, int, int, int] | tuple[float, float, float, float] | None = None, stroke_width: float | None = None, font_paths: list[str | Path] | None = None, track_baselines: bool = False, should_center: bool = True, height: float | None = None, **kwargs: Any)

基类:SVGMobject

A mobject rendered from a Typst markup string.

The Typst source is compiled to SVG via the typst Python package (a self-contained Rust binary extension — no system-level install required) and then imported through SVGMobject.

Parameters

typst_code

Raw Typst markup to be compiled. This string is placed verbatim into the body of a minimal Typst document.

font_size

Font size in Manim font-size units (default: DEFAULT_FONT_SIZE, i.e. 48). The actual scaling is applied after SVG import, matching the approach used by SingleStringMathTex.

typst_preamble

Extra Typst code inserted before the body. Useful for #import, #set, or #show rules. Default: "".

color

The color of the mobject. By default the standard VMobject color (white in dark mode). Overrides the Typst text fill color.

stroke_width

SVG stroke width override. If None (default), the stroke widths from Typst's SVG output are preserved.

font_paths

Optional list of additional font directories passed to the Typst compiler (e.g. for custom fonts not installed system-wide).

track_baselines

Whether to keep enough per-element reference data to recover the current Typst baseline frame for each imported submobject. When enabled, baseline_frames and get_baseline_frame() can be used to retrieve the current (orig, right, up) positions for the imported SVG elements.

should_center

Whether to center the mobject after import (default True).

height

Target height of the mobject. If None (default), the height is determined by font_size.

**kwargs

Forwarded to SVGMobject.

Examples

class TypstExample(Scene):
    def construct(self):
        formula = Typst(r"$ integral_a^b f(x) dif x $")
        self.play(Write(formula))
class TypstTextExample(Scene):
    def construct(self):
        text = Typst(
            r"*Hello* from _Typst!_",
            font_size=72,
        )
        self.add(text)
property baseline_frames: list[tuple[ndarray, ndarray, ndarray]]

Current Typst baseline frames for all tracked leaf submobjects.

property font_size: float

The font size of the Typst mobject.

get_baseline_frame(submobject: VMobject) → tuple[ndarray, ndarray, ndarray]

Return the current Typst baseline frame for a tracked submobject.

The returned tuple contains the current positions of (orig, right, up). These are recovered from the stored reference frame and the submobject's current affine position in the scene.

get_mob_from_shape_element(shape: SVGElement) → VMobject | None

Attach Typst-specific metadata to imported shape mobjects.

property hash_seed: tuple

Include baseline tracking in the SVG cache key.

init_colors(propagate_colors: bool = True) → Self

Recolor black submobjects to self.color.

Typst renders text in black (fill="#000000") by default. This mirrors the approach of SingleStringMathTex.init_colors(): any submobject whose color is black is recolored to self.color, while explicitly colored submobjects (non-black) are preserved.

modify_xml_tree(element_tree: ElementTree) → ElementTree

Convert data-typst-label attributes to id before parsing.

Typst's SVG renderer emits data-typst-label on <g> elements that carry a label (created via #box(body) <label>). The svgelements library propagates custom data-* attributes from parent groups to all children, making them unusable as unique group keys. id attributes, on the other hand, are not inherited.

This method walks the XML tree and promotes every data-typst-label to id (on <g> elements only), so that get_mobjects_from() can pick them up via its existing id-based grouping logic.

scale(scale_factor: float, scale_stroke: bool = False, *, about_point: ndarray | None = None, about_edge: ndarray | None = None) → Self

Scale the size by a factor.

Default behavior is to scale about the center of the vmobject.

Parameters
scale_factor

The scaling factor \(\alpha\). If \(0 < |\alpha| < 1\), the mobject will shrink, and for \(|\alpha| > 1\) it will grow. Furthermore, if \(\alpha < 0\), the mobject is also flipped.

scale_stroke

Boolean determining if each submobject's outline is scaled when the object is scaled. If enabled, each submobject keeps its relative stroke width (for example, a submobject with a 2px outline scaled by a factor of .5 will have a 1px outline, while a submobject with 0px stroke remains at 0px).

kwargs

Additional keyword arguments passed to scale().

Returns
VMobject

self

Examples
class MobjectScaleExample(Scene):
    def construct(self):
        c1 = Circle(1, RED).set_x(-1)
        c2 = Circle(1, GREEN).set_x(1)

        vg = VGroup(c1, c2)
        vg.set_stroke(width=50)
        self.add(vg)

        self.play(
            c1.animate.scale(.25),
            c2.animate.scale(.25,
                scale_stroke=True)
        )
See also

move_to()

select(key: str | int) → VGroup

Select a labeled sub-expression.

Labels are created in the Typst source either manually via the manimgrp helper or automatically through the {{ }} double-brace notation in MathTypst.

Parameters
key

A label name (str) matching a data-typst-label in the SVG, or an integer index into the auto-numbered {{ }} groups (_grp-0, _grp-1, …).

Returns
VGroup

The submobjects corresponding to the selected group.

Raises
KeyError

If no group with the given label exists.

IndexError

If an integer index is out of range.

Examples
class TypstSelectExample(Scene):
    def construct(self):
        eq = MathTypst(
            "{{ a + b : num }} / {{ c : den }} = {{ lambda }} {{ x }}"
        )
        eq.select("num").set_color(RED)  # "a + b"
        eq.select("den").set_color(BLUE) # "c"
        eq.select(0).set_color(YELLOW)   # "lambda" (auto-numbered: "grp-0")
        eq.select(1).set_color(GREEN)    # "x" (auto-numbered: "grp-1")

        self.add(eq)

Variable

名字 + 数值的组合显示:变量名在上数值在下,配 ValueTracker 实时联动。

继承关系

digraph G { graph [rankdir=LR, bgcolor="transparent", splines=spline, concentrate=true, nodesep="0.15", ranksep="0.3"]; node [shape=box, penwidth=0, width=0.05, height=0.05, margin=0.05]; edge [penwidth=1]; "Mobject" -> "VMobject"; "VMobject" -> "Variable"; }

参数

var

—,float

label

—

var_type

<class 'manim.mobject.text.…

num_decimal_places

2,int

快速上手

v = Variable(0, "x", num_decimal_places=2)

API 文档

class manim.Variable(var: float, label: str | Tex | MathTex | Text | SingleStringMathTex, var_type: type[DecimalNumber | Integer] = <class 'manim.mobject.text.numbers.DecimalNumber'>, num_decimal_places: int = 2, **kwargs: Any)

基类:VMobject

A class for displaying text that shows "label = value" with the value continuously updated from a ValueTracker.

Parameters

var

The initial value you need to keep track of and display.

label

The label for your variable. Raw strings are convertex to MathTex objects.

var_type

The class used for displaying the number. Defaults to DecimalNumber.

num_decimal_places

The number of decimal places to display in your variable. Defaults to 2. If var_type is an Integer, this parameter is ignored.

kwargs

Other arguments to be passed to ~.Mobject.

Attributes

labelUnion[str, Tex, MathTex, Text, SingleStringMathTex]

The label for your variable, for example x = ....

trackerValueTracker

Useful in updating the value of your variable on-screen.

valueUnion[DecimalNumber, Integer]

The tex for the value of your variable.

Examples

Normal usage:

# DecimalNumber type
var = 0.5
on_screen_var = Variable(var, Text("var"), num_decimal_places=3)
# Integer type
int_var = 0
on_screen_int_var = Variable(int_var, Text("int_var"), var_type=Integer)
# Using math mode for the label
on_screen_int_var = Variable(int_var, "{a}_{i}", var_type=Integer)
class VariablesWithValueTracker(Scene):
    def construct(self):
        var = 0.5
        on_screen_var = Variable(var, Text("var"), num_decimal_places=3)

        # You can also change the colours for the label and value
        on_screen_var.label.set_color(RED)
        on_screen_var.value.set_color(GREEN)

        self.play(Write(on_screen_var))
        # The above line will just display the variable with
        # its initial value on the screen. If you also wish to
        # update it, you can do so by accessing the `tracker` attribute
        self.wait()
        var_tracker = on_screen_var.tracker
        var = 10.5
        self.play(var_tracker.animate.set_value(var))
        self.wait()

        int_var = 0
        on_screen_int_var = Variable(
            int_var, Text("int_var"), var_type=Integer
        ).next_to(on_screen_var, DOWN)
        on_screen_int_var.label.set_color(RED)
        on_screen_int_var.value.set_color(GREEN)

        self.play(Write(on_screen_int_var))
        self.wait()
        var_tracker = on_screen_int_var.tracker
        var = 10.5
        self.play(var_tracker.animate.set_value(var))
        self.wait()

        # If you wish to have a somewhat more complicated label for your
        # variable with subscripts, superscripts, etc. the default class
        # for the label is MathTex
        subscript_label_var = 10
        on_screen_subscript_var = Variable(subscript_label_var, "{a}_{i}").next_to(
            on_screen_int_var, DOWN
        )
        self.play(Write(on_screen_subscript_var))
        self.wait()
class VariableExample(Scene):
    def construct(self):
        start = 2.0

        x_var = Variable(start, 'x', num_decimal_places=3)
        sqr_var = Variable(start**2, 'x^2', num_decimal_places=3)
        Group(x_var, sqr_var).arrange(DOWN)

        sqr_var.add_updater(lambda v: v.tracker.set_value(x_var.tracker.get_value()**2))

        self.add(x_var, sqr_var)
        self.play(x_var.tracker.animate.set_value(5), run_time=2, rate_func=linear)
        self.wait(0.1)