Widgets¶
Controls for drawing functions, notebook panels and sweeps. svg.explore and svg.sweep are exported at
the top level as well; the guide is Widgets.
|
Show function's drawing beside a panel of controls, redrawn as they change. |
|
Step function's parameters over time and return the animation as a scene. |
|
Declare the controls of a drawing function, by parameter name. |
|
The control a shorthand stands for. |
|
The controls of function: those declared with |
Live controls for drawing functions: notebook panels, preview forms and parameter sweeps.
A control is pure data (Slider, Segmented, ColorPicker, …), so one declaration
drives a notebook panel (explore(), the widget extra), the form of svgwriter preview and an
animation over time (sweep()). Shorthands stand in for controls: (0, 10) is a slider,
["a", "b"] a row of buttons, True a toggle and "#ff6347" a colour picker.
Example
>>> import svgwriter as svg
>>> @svg.widgets.controls(radius=(0, 30), color=["tomato", "gold", "teal"])
... def dot(radius=10, color="tomato"):
... return svg.circle(30, 30, radius, fill=color)
>>> view = svg.explore(dot, backend=svg.widgets.Recorder()) # a panel in a notebook
>>> view.update(radius=25).code()
"dot(radius=25, color='tomato')"
>>> svg.sweep(dot, radius=(5, 30), dur=1).values_at(0.5)
{'color': 'tomato', 'radius': 18}
- class Backend(*args, **kwargs)[source]¶
Bases:
ProtocolWhat shows an
Interactive: a panel of inputs, the drawing and the last error.The notebook backend uses ipywidgets; tests and other front ends supply their own.
- class Checkbox(value: bool = False, *, label: str | None = None)[source]¶
Bases:
ToggleOn or off, shown as a box to tick.
- Parameters:
value (bool, optional) – The starting state. Defaults to False.
Examples
>>> import svgwriter as svg >>> svg.widgets.Checkbox().check(True) True
- check(value: Any) bool¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- class ColorPicker(value: Any = '#000000', *, label: str | None = None)[source]¶
Bases:
ControlAny colour; the drawing function receives it as
#rrggbb(#rrggbbaawhen translucent).Examples
>>> import svgwriter as svg >>> svg.widgets.ColorPicker("tomato").initial '#ff6347'
- check(value: Any) str[source]¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- class Control(*, label: str | None = None)[source]¶
Bases:
objectOne adjustable parameter: pure data, read the same way by notebooks,
svgwriter previewand sweeps.Subclasses add their own
valueand checks; a control does not hold the current value of a panel, only its starting value.- Parameters:
label (str, optional) – Shown beside the input. Defaults to None, the parameter name with underscores as spaces.
See also
svgwriter.tools.widgets.controlBuild a control from shorthand such as
(0, 10).
Examples
>>> import svgwriter as svg >>> radius = svg.widgets.Slider(0, 20, label="corner radius") >>> radius.initial, radius.check(4) (10.0, 4.0)
- property initial: Any¶
valuewhen given, else a natural default (a slider’s middle, the first option).- Returns:
object – A value that passes
check().
Examples
>>> import svgwriter as svg >>> svg.widgets.Segmented(["a", "b"]).initial 'a'
- Type:
The starting value
- check(value: Any) Any[source]¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- from_form(raw: Any) Any[source]¶
The value a form field sends: options arrive as indices, everything else as the value itself.
- Parameters:
raw (object) – What the input produced (a JSON value).
- Returns:
object – The checked value.
- Raises:
ValueError – If the value is invalid.
Examples
>>> import svgwriter as svg >>> svg.widgets.Dropdown(["low", "high"]).from_form(1) 'high'
- argument(value: Any) Any[source]¶
What the drawing function receives for value (a
Lengthfor sliders in a unit).- Parameters:
value (object) – A checked value.
- Returns:
object – The argument.
Examples
>>> import svgwriter as svg >>> str(svg.widgets.Slider(0, 10, units="mm").argument(4.0)) '4mm'
- code(value: Any) str[source]¶
value as Python source, for
Interactive.code.- Parameters:
value (object) – A checked value.
- Returns:
str – A Python expression.
Examples
>>> import svgwriter as svg >>> svg.widgets.Text("Hi").code("Hi") "'Hi'"
- text(value: Any) str[source]¶
value as a short readout for the panel.
- Parameters:
value (object) – A checked value.
- Returns:
str – The readout.
Examples
>>> import svgwriter as svg >>> svg.widgets.Slider(0, 1, format=".0%").text(0.25) '25%'
- titled(name: str) C[source]¶
This control with a label derived from name when it has none.
- Parameters:
name (str) – The parameter name.
- Returns:
Control – A copy with a label.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().titled("show_grid").label 'show grid'
- starting_at(value: Any) C[source]¶
This control starting at value instead.
- Parameters:
value (object) – The new starting value.
- Returns:
Control – A copy.
- Raises:
ValueError – If value does not pass
check().
Examples
>>> import svgwriter as svg >>> svg.widgets.Slider(0, 10).starting_at(3).initial 3.0
- class Dropdown(options: Sequence[Any] | Mapping[str, Any], value: Any = None, *, label: str | None = None)[source]¶
Bases:
ControlOne of several options, from a menu.
- Parameters:
- Raises:
ValueError – If there are no options or value is not one of them.
See also
SegmentedThe same as a row of buttons.
Examples
>>> import svgwriter as svg >>> weight = svg.widgets.Dropdown({"light": 300, "bold": 700}) >>> weight.initial, weight.labels (300, ('light', 'bold'))
- index(value: Any) int[source]¶
The position of value among the options.
- Parameters:
value (object) – One of the options’ values.
- Returns:
int – Its index.
- Raises:
ValueError – If it is not an option.
Examples
>>> import svgwriter as svg >>> svg.widgets.Segmented(["S", "M", "L"]).index("L") 2
- check(value: Any) Any[source]¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- from_form(raw: Any) Any[source]¶
The value a form field sends: options arrive as indices, everything else as the value itself.
- Parameters:
raw (object) – What the input produced (a JSON value).
- Returns:
object – The checked value.
- Raises:
ValueError – If the value is invalid.
Examples
>>> import svgwriter as svg >>> svg.widgets.Dropdown(["low", "high"]).from_form(1) 'high'
- class IntSlider(min: float | Length, max: float | Length, step: float | None = None, value: float | Length | None = None, *, label: str | None = None, units: str | None = None, format: str | None = None)[source]¶
Bases:
SliderA whole number between two ends; the step defaults to 1.
- Parameters:
See also
SliderAny number.
Examples
>>> import svgwriter as svg >>> svg.widgets.IntSlider(1, 12).initial 6
- argument(value: Any) Any¶
What the drawing function receives for value (a
Lengthfor sliders in a unit).- Parameters:
value (object) – A checked value.
- Returns:
object – The argument.
Examples
>>> import svgwriter as svg >>> str(svg.widgets.Slider(0, 10, units="mm").argument(4.0)) '4mm'
- check(value: Any) float | int¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- code(value: Any) str¶
value as Python source, for
Interactive.code.- Parameters:
value (object) – A checked value.
- Returns:
str – A Python expression.
Examples
>>> import svgwriter as svg >>> svg.widgets.Text("Hi").code("Hi") "'Hi'"
- class Interactive(function: Callable[[...], Any], controls: Mapping[str, Control], backend: Backend, delay: float = 0.08)[source]¶
Bases:
objectA drawing function with live controls;
explore()makes one.- Parameters:
function (callable) – Returns a
Documentor an element for keyword arguments named like the controls.controls (mapping of str to Control) – One control per parameter.
backend (Backend) – What shows the panel.
delay (float, optional) – Seconds to wait after the last change before redrawing. Defaults to 0.08; 0 redraws at once.
- Variables:
See also
exploreBuild and show one in a notebook.
Examples
>>> import svgwriter as svg >>> from svgwriter.tools.widgets import Interactive, Slider >>> class Quiet: ... def panel(self, controls, values, changed): pass ... def draw(self, svg): pass ... def fail(self, message): pass ... def show(self): pass >>> dot = Interactive(lambda r: svg.circle(10, 10, r), {"r": Slider(1, 10)}, Quiet(), delay=0) >>> dot.update(r=4).code() '<lambda>(r=4.0)'
- property values: dict[str, Any]¶
The current value of every control, by name.
- Returns:
dict – A copy; change values with
update().
Examples
>>> import svgwriter as svg >>> svg.explore(lambda n=3: svg.text(str(n)), backend=svg.widgets.Recorder()).values {'n': 3}
- property document: Document¶
The drawing for the current values.
- Returns:
Document – The last drawing made; after an error, the last one that worked.
- Raises:
RuntimeError – If no drawing has worked yet.
Examples
>>> import svgwriter as svg >>> view = svg.explore(lambda r=5: svg.circle(r, r, r), backend=svg.widgets.Recorder()) >>> view.document.root[0].tag 'circle'
- update(**values: Any) Interactive[source]¶
Set controls by name and redraw at once.
- Parameters:
**values (object) – New values, checked by their controls.
- Returns:
Interactive – Itself, for chaining.
- Raises:
KeyError – If a name is not a control.
ValueError – If a value fails its control’s check.
Examples
>>> import svgwriter as svg >>> view = svg.explore(lambda r=5: svg.circle(r, r, r), backend=svg.widgets.Recorder()) >>> view.update(r=8).values {'r': 8}
- redraw() None[source]¶
Draw the current values (from the cache when they were drawn before) and show the result.
On an error the previous drawing stays and the traceback is shown under it.
Examples
>>> import svgwriter as svg >>> view = svg.explore(lambda r=5: svg.circle(r, r, r), backend=svg.widgets.Recorder()) >>> view.redraw()
- save(path: AnyPath, **options: Any) Path[source]¶
Save the drawing for the current values; the extension picks the format.
- Parameters:
path (str or path-like) – The file to write (
.svg,.png,.pdf, …).**options (object) – Passed to
Document.save.
- Returns:
pathlib.Path – The written file.
Examples
>>> import svgwriter as svg >>> view = svg.explore(lambda r=5: svg.circle(r, r, r), backend=svg.widgets.Recorder()) >>> view.save("dot.svg")
- code() str[source]¶
The call that draws the current state, for copying into a script.
- Returns:
str –
name(param=value, ...).
Examples
>>> import svgwriter as svg >>> def card(rank="A", glow=False): ... return svg.text(rank) >>> svg.explore(card, backend=svg.widgets.Recorder()).update(glow=True).code() "card(rank='A', glow=True)"
- class MultiSelect(options: Sequence[Any] | Mapping[str, Any], value: Sequence[Any] = (), *, label: str | None = None)[source]¶
Bases:
DropdownAny number of options; the value is a tuple in option order.
- Parameters:
options (sequence or mapping) – The choices, or
{label: value}.value (sequence, optional) – The starting choices. Defaults to none.
Examples
>>> import svgwriter as svg >>> layers = svg.widgets.MultiSelect(["grid", "guides", "labels"], value=["labels", "grid"]) >>> layers.initial, layers.from_form([1]) (('grid', 'labels'), ('guides',))
- check(value: Any) tuple[Any, ...][source]¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- from_form(raw: Any) tuple[Any, ...][source]¶
The value a form field sends: options arrive as indices, everything else as the value itself.
- Parameters:
raw (object) – What the input produced (a JSON value).
- Returns:
object – The checked value.
- Raises:
ValueError – If the value is invalid.
Examples
>>> import svgwriter as svg >>> svg.widgets.Dropdown(["low", "high"]).from_form(1) 'high'
- text(value: Any) str[source]¶
value as a short readout for the panel.
- Parameters:
value (object) – A checked value.
- Returns:
str – The readout.
Examples
>>> import svgwriter as svg >>> svg.widgets.Slider(0, 1, format=".0%").text(0.25) '25%'
- index(value: Any) int¶
The position of value among the options.
- Parameters:
value (object) – One of the options’ values.
- Returns:
int – Its index.
- Raises:
ValueError – If it is not an option.
Examples
>>> import svgwriter as svg >>> svg.widgets.Segmented(["S", "M", "L"]).index("L") 2
- class Number(value: float = 0.0, min: float | None = None, max: float | None = None, step: float | None = None, *, label: str | None = None, units: str | None = None, format: str | None = None)[source]¶
Bases:
_NumericA typed-in number, optionally bounded; whole numbers when value is an int.
- Parameters:
Examples
>>> import svgwriter as svg >>> count = svg.widgets.Number(5, min=1) >>> count.check(8), count.text(8) (8, '8')
- check(value: Any) float | int[source]¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- argument(value: Any) Any¶
What the drawing function receives for value (a
Lengthfor sliders in a unit).- Parameters:
value (object) – A checked value.
- Returns:
object – The argument.
Examples
>>> import svgwriter as svg >>> str(svg.widgets.Slider(0, 10, units="mm").argument(4.0)) '4mm'
- code(value: Any) str¶
value as Python source, for
Interactive.code.- Parameters:
value (object) – A checked value.
- Returns:
str – A Python expression.
Examples
>>> import svgwriter as svg >>> svg.widgets.Text("Hi").code("Hi") "'Hi'"
- class RangeSlider(min: float, max: float, step: float | None = None, value: tuple[float, float] | None = None, integer: bool = False, *, label: str | None = None, units: str | None = None, format: str | None = None)[source]¶
Bases:
_NumericA pair of numbers
(low, high)between two ends.- Parameters:
Examples
>>> import svgwriter as svg >>> band = svg.widgets.RangeSlider(0, 100) >>> band.initial, band.check((20, 80)) ((0.0, 100.0), (20.0, 80.0))
- check(value: Any) tuple[float, float][source]¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- argument(value: Any) Any¶
What the drawing function receives for value (a
Lengthfor sliders in a unit).- Parameters:
value (object) – A checked value.
- Returns:
object – The argument.
Examples
>>> import svgwriter as svg >>> str(svg.widgets.Slider(0, 10, units="mm").argument(4.0)) '4mm'
- code(value: Any) str¶
value as Python source, for
Interactive.code.- Parameters:
value (object) – A checked value.
- Returns:
str – A Python expression.
Examples
>>> import svgwriter as svg >>> svg.widgets.Text("Hi").code("Hi") "'Hi'"
- class Recorder[source]¶
Bases:
objectA
Backendthat shows nothing and remembers everything;set()plays a user’s edit.- Variables:
See also
svgwriter.tools.widgets.exploreTakes
backend=Recorder().
Examples
>>> import svgwriter as svg >>> panel = svg.widgets.Recorder() >>> view = svg.explore(lambda size=10: svg.rect(0, 0, size, size), backend=panel, delay=0) >>> panel.set("size", 15) >>> view.values, len(panel.drawings) ({'size': 15}, 2)
- panel(controls: Mapping[str, Control], values: Mapping[str, Any], changed: Callable[[str, Any], None]) None[source]¶
- set(name: str, raw: Any) None[source]¶
Change input name to raw, as a person would (option controls take an index).
- Parameters:
- Raises:
RuntimeError – If no panel was built.
Examples
>>> import svgwriter as svg >>> panel = svg.widgets.Recorder() >>> view = svg.explore(lambda suit="♠": svg.text(suit), suit=["♠", "♥"], backend=panel, delay=0) >>> panel.set("suit", 1) >>> view.values {'suit': '♥'}
- class Segmented(options: Sequence[Any] | Mapping[str, Any], value: Any = None, *, label: str | None = None)[source]¶
Bases:
DropdownOne of a few options, as a row of buttons.
- Parameters:
options (sequence or mapping) – The choices, or
{label: value}.value (object, optional) – The starting choice. Defaults to the first.
Examples
>>> import svgwriter as svg >>> svg.widgets.Segmented(["♠", "♥"]).from_form(1) '♥'
Notes
Backends show up to six options as buttons and more than that as a dropdown, see
compact.- check(value: Any) Any¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- from_form(raw: Any) Any¶
The value a form field sends: options arrive as indices, everything else as the value itself.
- Parameters:
raw (object) – What the input produced (a JSON value).
- Returns:
object – The checked value.
- Raises:
ValueError – If the value is invalid.
Examples
>>> import svgwriter as svg >>> svg.widgets.Dropdown(["low", "high"]).from_form(1) 'high'
- index(value: Any) int¶
The position of value among the options.
- Parameters:
value (object) – One of the options’ values.
- Returns:
int – Its index.
- Raises:
ValueError – If it is not an option.
Examples
>>> import svgwriter as svg >>> svg.widgets.Segmented(["S", "M", "L"]).index("L") 2
- class Slider(min: float | Length, max: float | Length, step: float | None = None, value: float | Length | None = None, *, label: str | None = None, units: str | None = None, format: str | None = None)[source]¶
Bases:
_NumericA number between two ends.
- Parameters:
step (float, optional) – The increment. Defaults to None, a hundredth of the range.
value (float, optional) – The starting value. Defaults to None, the middle of the range.
label (str, optional) – Shown beside the slider.
units (str, optional) – Shown after the readout. A length unit (
"mm","pt","px", …) also makes the drawing function receive aLengthin that unit. Defaults to None.format (str, optional) – A format spec for the readout (
".1f","{:.0f}°"). Defaults to None (:g).
- Raises:
ValueError – If
min >= max, the step is not positive or the value is out of range.
See also
IntSliderWhole numbers.
RangeSliderA pair of numbers.
Examples
>>> import svgwriter as svg >>> hue = svg.widgets.Slider(0, 360, step=1, format="{:.0f}°") >>> hue.initial, hue.text(120) (180.0, '120°') >>> svg.widgets.Slider(0, 10, units="mm").argument(2.5) Length(value=2.5, unit=<Unit.MM: 'mm'>)
- check(value: Any) float | int[source]¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- argument(value: Any) Any¶
What the drawing function receives for value (a
Lengthfor sliders in a unit).- Parameters:
value (object) – A checked value.
- Returns:
object – The argument.
Examples
>>> import svgwriter as svg >>> str(svg.widgets.Slider(0, 10, units="mm").argument(4.0)) '4mm'
- code(value: Any) str¶
value as Python source, for
Interactive.code.- Parameters:
value (object) – A checked value.
- Returns:
str – A Python expression.
Examples
>>> import svgwriter as svg >>> svg.widgets.Text("Hi").code("Hi") "'Hi'"
- class Sweep(function: Callable[[...], Any], tracks: Mapping[str, Callable[[float], Any]], fixed: Mapping[str, Any], *, duration: float, fps: float | None = None, ease: Ease | str | tuple[float, float, float, float] | tuple[Any, ...] | Callable[[float], float] | None = None, name: str | None = None)[source]¶
Bases:
SceneA drawing function called with parameters that change over time;
sweep()makes one.A
Scene:save()writes GIF and MP4 through ffmpeg and bakes SVG, HTML and PowerPoint into SMIL. Each frame redraws the function and carries the result over onto the scene’s drawing, so elements that keep their place change attributes smoothly in the baked SVG.- Parameters:
function (callable) – Returns a
Documentor an element.tracks (mapping of str to callable) – For each swept parameter, its value at progress
0..1.fixed (mapping of str to object) – Arguments that do not change.
duration (float) – Seconds from the first value to the last.
fps (float, optional) – Frames per second. Defaults to the scene default, 30.
ease (str, tuple or callable, optional) – A timing curve as
Easetakes. Defaults to None (linear).name (str, optional) – Output name. Defaults to the function’s name.
See also
sweepBuild one from ranges and lists.
Examples
>>> import svgwriter as svg >>> from svgwriter.tools.widgets import Sweep >>> grow = Sweep(lambda r: svg.circle(20, 20, r), {"r": lambda p: 2 + 18 * p}, {}, duration=1.0, fps=4) >>> grow.values_at(0.5) {'r': 11.0}
- fps = 30.0¶
- duration = None¶
- width = 640.0¶
- height = 360.0¶
- values_at(seconds: float) dict[str, Any][source]¶
The arguments at seconds.
- Parameters:
seconds (float) – Time since the start; clamped to the duration.
- Returns:
dict – One value per parameter, swept and fixed.
Examples
>>> import svgwriter as svg >>> fade = svg.sweep(lambda tone: svg.rect(0, 0, 10, 10, fill=tone), tone=("#000000", "#ffffff")) >>> fade.values_at(1.0) {'tone': '#808080'}
- update(seconds: float) None[source]¶
Redraw the function for the values at seconds onto the scene’s drawing.
- Parameters:
seconds (float) – Time since the start.
Examples
>>> import svgwriter as svg >>> grow = svg.sweep(lambda r: svg.circle(20, 20, r), r=(2, 20), dur=1) >>> grow.update(1.0) >>> grow.document.root[0].get("r") 20.0
- save(path: AnyPath | None = None, *, fps: float | None = None, duration: float | None = None, renderer: Renderer | str | None = None, ffmpeg: str | None = None) Path[source]¶
Save the sweep;
.gifis encoded here, frame by frame, without ffmpeg.- Parameters:
path (str or path-like, optional) – Output file; the extension picks the format as for
Scene.save. Defaults to<name>.mp4.fps (float, optional) – Overrides the sweep’s
fps.duration (float, optional) – Overrides the sweep’s duration.
renderer (callable or str, optional) – The renderer for video formats.
ffmpeg (str, optional) – The ffmpeg executable for video formats.
- Returns:
pathlib.Path – The written file.
Examples
>>> import svgwriter as svg >>> grow = svg.sweep(lambda r: svg.circle(20, 20, r), r=(2, 20), dur=1, fps=4) >>> grow.save("grow.gif")
- at(seconds: float) Document¶
The scene as it is at seconds: behaviors and
update()run, SMIL sampled.- Parameters:
seconds (float) – The moment, from the start of the scene.
- Returns:
Document – A still copy, like
Document.at; the scene’s own document keeps the Python state of that moment.
See also
svgwriter.Document.atThe SMIL-only moment of a document.
Examples
>>> import svgwriter as svg >>> class Grow(svg.Scene): ... width, height = 10, 10 ... def build(self, doc): ... self.box = doc.rect(0, 0, 1, 1) ... def update(self, seconds): ... self.box.width = 1 + seconds >>> Grow().at(2).root[-1].get("width") 3
- attach(element: ~svgwriter.motion.video._scene_motion.E, behavior: ~collections.abc.Callable[[~typing.Concatenate[~svgwriter.motion.video._scene_motion.E, float, ~P]], None], *args: ~typing.~P, **kwargs: ~typing.~P) E¶
Run behavior on element before every frame:
behavior(element, seconds, *args, **kwargs).Typed with the behavior’s own options, so editors complete and check them. Behaviors run in the order they were attached, all before
update(). The first one attached to an element records itshome.element.animate.<name>(...)does the same for a behavior registered with@svg.preset.behavior.- Parameters:
element (Element) – What the behavior moves; usually already in
document.behavior (callable) –
behavior(element, seconds, *, option=default, ...); it need not be registered.*args – Passed on to behavior after the element and the time.
**kwargs – Passed on to behavior after the element and the time.
- Returns:
Element – element, so it can be kept in one line:
self.bell = self.attach(doc.rect(...), wiggle).
See also
bakeThe behaviors as SMIL.
Examples
>>> import svgwriter as svg >>> def slide(element: svg.Element, seconds: float, *, speed: float = 10) -> None: ... element.matrix = element.home.matrix ... element.translate(speed * seconds) >>> class Train(svg.Scene): ... width, height, duration = 60, 20, 2.0 ... def build(self, doc): ... self.car = self.attach(doc.rect(0, 5, 10, 10), slide, speed=20) >>> scene = Train() >>> scene.render(1.0)[:4] b'\x89PNG' >>> scene.car.matrix.e 20.0
- bake(fps: float | None = None, *, duration: float | None = None, tolerance: float = 0.01, loop: bool | None = None) Document¶
A copy of the document whose SMIL plays what the behaviors and
update()do.The scene is sampled
fpstimes a second. Each element’s changes become<animate>,<animateTransform>and<set>children with as few keyframes as keep every sample within tolerance: numbers and colours interpolate (a path’sdwhile its commands keep their shape), transforms split into translate, rotate, skew and scale, and other values switch with<set>. Changing text becomes one copy per text shown in turn, and elements added or removed are shown or hidden withvisibility. The document’s own SMIL is kept and plays on top, as in the video. Anything SMIL cannot express is left out and listed in one warning.- Parameters:
fps (float, optional) – Samples per second. Defaults to the scene’s
fps.duration (float, optional) – Seconds to sample. Defaults to the scene’s
duration, else the end of its SMIL.tolerance (float, optional) – Largest difference allowed between the baked animation and a sample, in user units, degrees, scale factors or colour channels (
0..1). Defaults to 0.01.loop (bool, optional) – Repeat forever: animations that span the whole duration from the start get
repeatCount="indefinite", so a seamless scene plays on in browsers and notebooks. Defaults to None, which uses the scene’sloopattribute (False unless the class sets it).
- Returns:
Document – The baked copy; the scene’s own document keeps its Python state.
- Raises:
ValueError – If no duration is set and the drawing has no SMIL animation.
See also
saveUses this for
.svg,.svgz,.htmland.pptx.
Notes
Baking runs the behaviors and
update()for every sample, so it leaves the scene at its last moment. What is not expressed: an element moved to another parent, changes of an id, CSS declarations that are not SVG properties, an attribute removed with no initial value to return to, and transforms squashed flat with a skew.Examples
>>> import svgwriter as svg >>> class Slide(svg.Scene): ... width, height, fps, duration = 100, 20, 10, 1.0 ... def build(self, doc): ... self.box = doc.rect(0, 5, 10, 10, fill="red") ... def update(self, seconds): ... self.box.x = 90 * seconds >>> baked = Slide().bake() >>> animation = baked[0].children[0] >>> animation.tag, animation.get("values"), animation.get("keyTimes") ('animate', '0;90', '0;1') >>> baked.at(0.5)[0].get("x") '45'
- build(doc: Document) None¶
Draw the scene into doc; called once, when the scene is created.
- Parameters:
doc (Document) – An empty document of size
widthbyheight.
See also
updateChange the drawing for each frame.
Examples
>>> import svgwriter as svg >>> class Card(svg.Scene): ... width, height = 80, 40 ... def build(self, doc): ... doc.rect(0, 0, 80, 40, fill="navy") >>> len(Card().document) 1
- property document: Document¶
The drawing the scene animates.
- Returns:
Document – The document passed in, or a new one filled by
build().
Examples
>>> import svgwriter as svg >>> svg.Scene().document.root.get("viewBox").width 640.0
- frames(*, fps: float | None = None, duration: float | None = None, renderer: Renderer | str | None = None) Iterator[Frame]¶
Render the frames without encoding them.
- Parameters:
- Yields:
Frame – One frame per
1 / fpsseconds.- Raises:
ValueError – If no duration is set and the drawing has no SMIL animation.
See also
saveEncode the frames into a file.
Examples
>>> import svgwriter as svg >>> class Blank(svg.Scene): ... width, height, duration = 8, 6, 1.0 >>> [(f.width, f.height) for f in Blank().frames(fps=2)] [(8, 6), (8, 6)]
- render(seconds: float = 0.0, *, scale: float = 1.0, background: ColorLike | None = None) bytes¶
One frame at seconds as PNG bytes, with SMIL applied.
- Parameters:
- Returns:
bytes – A PNG file.
See also
atThe still copy that is drawn.
Examples
>>> import svgwriter as svg >>> svg.Scene(svg.Document(4, 4)).render(scale=2)[:4] b'\x89PNG'
- renderer = 'skia'¶
- size = None¶
- class Swatches(options: Sequence[Any] | Mapping[str, Any], value: Any = None, *, label: str | None = None)[source]¶
Bases:
DropdownOne of several colours, as a row of colour chips.
- Parameters:
options (sequence of colour) – The colours, as given to the drawing function.
value (colour, optional) – The starting colour. Defaults to the first.
Examples
>>> import svgwriter as svg >>> svg.widgets.Swatches(["tomato", "#0ea5e9"]).chips ('#ff6347', '#0ea5e9')
- check(value: Any) Any¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- from_form(raw: Any) Any¶
The value a form field sends: options arrive as indices, everything else as the value itself.
- Parameters:
raw (object) – What the input produced (a JSON value).
- Returns:
object – The checked value.
- Raises:
ValueError – If the value is invalid.
Examples
>>> import svgwriter as svg >>> svg.widgets.Dropdown(["low", "high"]).from_form(1) 'high'
- index(value: Any) int¶
The position of value among the options.
- Parameters:
value (object) – One of the options’ values.
- Returns:
int – Its index.
- Raises:
ValueError – If it is not an option.
Examples
>>> import svgwriter as svg >>> svg.widgets.Segmented(["S", "M", "L"]).index("L") 2
- class Text(value: str = '', *, label: str | None = None)[source]¶
Bases:
ControlA line of text.
- Parameters:
value (str, optional) – The starting text. Defaults to
"".
Examples
>>> import svgwriter as svg >>> svg.widgets.Text("Hello").initial 'Hello'
- check(value: Any) str[source]¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- class Toggle(value: bool = False, *, label: str | None = None)[source]¶
Bases:
ControlOn or off, shown as a switch button.
- Parameters:
See also
CheckboxThe same as a box to tick.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle(True).initial True
- check(value: Any) bool[source]¶
Validate value and return it in the control’s own form (a float, a hex colour, an option).
- Parameters:
value (object) – A candidate value.
- Returns:
object – The normalized value.
- Raises:
ValueError – If the value is out of range or not an option.
TypeError – If the value has the wrong type.
Examples
>>> import svgwriter as svg >>> svg.widgets.Toggle().check(True) True
- control(spec: Any, *, label: str | None = None) Control[source]¶
The control a shorthand stands for.
Shorthand
Control
a
Controlitself
True/False(0, 10),(0, 1, 0.1)(svg.mm(0), svg.mm(20))Sliderin millimetres40,0.5,svg.mm(5)a slider from 0 to twice the value
"#ff6347", aColorany other str
["a", "b"],{"label": value}a list of colours
- Parameters:
- Returns:
Control – The control.
- Raises:
TypeError – If nothing matches spec.
ValueError – If the shorthand is malformed (a slider with
min >= max, no options).
See also
controlsDeclare the controls of a drawing function.
Examples
>>> import svgwriter as svg >>> svg.widgets.control((0, 10)) IntSlider(label=None, units=None, format=None, min=0, max=10, step=1, value=None) >>> type(svg.widgets.control(["♠", "♥", "♦", "♣"])).__name__, type(svg.widgets.control(list("ABCDE"))).__name__ ('Segmented', 'Dropdown') >>> svg.widgets.control(svg.mm(5)).units 'mm'
- controls(**specs: Any) Callable[[F], F][source]¶
Declare the controls of a drawing function, by parameter name.
explore(),sweep()andsvgwriter previewread them, andsvgwriter buildcalls the function with their starting values.- Parameters:
**specs (object) – A control or a shorthand (see
control()) per parameter.- Returns:
callable – A decorator that returns the function unchanged, with the controls attached.
- Raises:
TypeError – If a name is not a parameter of the function, or a shorthand matches no control.
See also
controls_ofThe controls a function ends up with.
Examples
>>> import svgwriter as svg >>> @svg.widgets.controls(radius=(0, 40), filled=False) ... def badge(doc, radius=12, filled=True): ... doc.circle(50, 50, radius, fill="tomato" if filled else "none", stroke="black") >>> {name: c.initial for name, c in svg.widgets.controls_of(badge).items()} {'radius': 12, 'filled': False}
- controls_of(function: Callable[[...], Any], *, infer: bool = True, **specs: Any) dict[str, Control][source]¶
The controls of function: those declared with
controls(), then specs, labelled by name.With neither, controls are inferred from the function’s keyword defaults where a shorthand matches (
size=40gives a slider,glow=Falsea toggle). A control without a starting value starts at the function’s default for that parameter.- Parameters:
- Returns:
dict of str to Control – One control per parameter, in declaration order.
- Raises:
TypeError – If a name is not a parameter of the function.
Examples
>>> import svgwriter as svg >>> def ring(size=40, glow=False, label="Hi"): ... return svg.circle(0, 0, size) >>> {name: type(c).__name__ for name, c in svg.widgets.controls_of(ring).items()} {'size': 'IntSlider', 'glow': 'Toggle', 'label': 'Text'}
- explore(function: Callable[[...], Any], *, backend: Backend | None = None, delay: float = 0.08, **controls: Any) Interactive[source]¶
Show function’s drawing beside a panel of controls, redrawn as they change.
The function returns a
Documentor an element; a function whose first parameter is not a control (a project’sbuild(doc, ...)) receives a new document there. Redraws wait for the controls to settle, repeated values come from a cache, and an error keeps the previous drawing with the traceback under it.- Parameters:
function (callable) – The drawing function.
backend (Backend, optional) – What shows the panel. Defaults to None, ipywidgets in a notebook.
delay (float, optional) – Seconds to wait after the last change before redrawing. Defaults to 0.08.
**controls (object) – A
Controlor a shorthand per parameter (seecontrol()), added to those declared withcontrols(). With none at all, they are inferred from the function’s keyword defaults.
- Returns:
Interactive –
.values,.document,.save(path)and.code()for the current state.- Raises:
ImportError – Without a backend when ipywidgets is not installed (
pip install pysvgwriter[widget]).TypeError – If a control names no parameter of function.
See also
sweepStep the same parameters over time instead.
Examples
>>> import svgwriter as svg >>> def badge(radius=12, color="#0ea5e9"): ... return svg.circle(radius, radius, radius, fill=color) >>> view = svg.explore(badge, radius=(4, 40), color=["#0ea5e9", "#f43f5e"], backend=svg.widgets.Recorder()) >>> view.update(radius=30).code() "badge(radius=30, color='#0ea5e9')"
- sweep(function: Callable[[...], Any], *, dur: float = 2.0, fps: float | None = None, ease: Ease | str | tuple[float, float, float, float] | tuple[Any, ...] | Callable[[float], float] | None = None, name: str | None = None, **params: Any) Sweep[source]¶
Step function’s parameters over time and return the animation as a scene.
Each keyword is a parameter:
(start, end)of numbers, lengths or colours runs smoothly from one to the other (whole numbers when the parameter is declared with anIntSlider); a list steps through its items; a slider runs from itsminto itsmax, options and toggles step through their values. Anything else is passed unchanged, and parameters with declared controls (controls()) that are not given keep their starting value.- Parameters:
function (callable) – Returns a
Documentor an element.dur (float, optional) – Seconds from start to end. Defaults to 2.
fps (float, optional) – Frames per second. Defaults to 30.
ease (str, tuple or callable, optional) – Timing curve (
"ease-in-out", …). Defaults to None (linear).name (str, optional) – Output name. Defaults to the function’s name.
**params (object) – Ranges, lists, controls and fixed values, by parameter name.
- Returns:
Sweep – A scene:
.save("x.svg")bakes SMIL;.gif,.mp4and.pptxwork as for any scene.- Raises:
TypeError – If a range mixes kinds or a name is not a parameter.
See also
exploreThe same parameters on live controls.
Examples
>>> import svgwriter as svg >>> def bar(width=10, color="#0ea5e9"): ... return svg.rect(0, 0, width, 10, fill=color) >>> growing = svg.sweep(bar, width=(10, 90), dur=1, fps=4) >>> [growing.values_at(t)["width"] for t in (0, 0.5, 1)] [10.0, 50.0, 90.0] >>> growing.save("bar.svg")