build123d icon indicating copy to clipboard operation
build123d copied to clipboard

Proposed python turtle example

Open jdegenstein opened this issue 1 year ago • 1 comments

Adapted from me and @snoyer:

Still need to add some explanatory comments.

Inspired by https://mathcurve.com/courbes2d.gb/giration/motifs.shtml

from build123d import *
import tkinter
import turtle
from contextlib import contextmanager
from math import cos, radians

@contextmanager
def b3d_turtle():
    main = tkinter.Tk()
    main.withdraw()
    canv = tkinter.Canvas(master=main)
    trtl = turtle.RawTurtle(canv)
    trtl.screen.tracer(0, 0)
    yield trtl

with b3d_turtle() as trtl:
    def meanderc(i, a=0.96, b=2, n=10, samples=1000):
        resample = 7200/samples
        c = 1 / n / b
        return resample*(a * cos(radians(resample*i / b)) + c)

    trtl.begin_poly()

    iters = 300
    for i in range(0, iters):
        trtl.forward(1)
        trtl.right(meanderc(i, samples=iters))

    trtl.end_poly()

with BuildPart() as p:
    with BuildSketch() as s:
        with BuildLine() as l:
            Spline(trtl.get_poly(), periodic=False)
        make_face()
    extrude(amount=-10)

Image

jdegenstein avatar Jan 29 '25 21:01 jdegenstein

you really went digging for that one!

Is there a use for a context manager with no closing (nothing after the yield)? For this use-case would it be more straightforward to have something like:

def offscreen_turtle():
    """a turtle that doesn't show a drawing window."""
    tk = tkinter.Tk()
    tk.withdraw()
    trtl = turtle.RawTurtle(tkinter.Canvas(master=tk))
    trtl.screen.tracer(0, 0)  # remove delays by disabling animation
    return trtl

trtl = offscreen_turtle()
trtl.begin_poly()
...

snoyer avatar Jan 30 '25 09:01 snoyer