You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用sketchpy调用draw函数遇NameError问题及替代方案求助

解决sketchpy报错及Turtle绘图替代方案

修复sketchpy代码错误

你遇到的NameError是因为代码逻辑写错了:draw不是全局函数,而是sketch_from_image创建的对象的方法,且SVG路径无需file://前缀。修正后的代码如下:

from sketchpy import canvas
# 直接使用本地文件路径,移除file://前缀
obj = canvas.sketch_from_image('C:/Users/aryan_mukhi/Downloads/32fd871166ae8debb1f848664365963f_adobe_express.svg')
# 调用对象的draw方法,而非直接使用draw函数
obj.draw(threshold=127)

如果仍有问题,建议将SVG转为PNG格式后再尝试,sketchpy对SVG的支持相对有限。

无需sketchpy的替代方案

方案1:PIL+Turtle手动实现逐像素绘图

通过PIL处理图片灰度信息,再用Turtle根据灰度值完成绘制:

import turtle
from PIL import Image

# 加载图片并转为灰度模式
img = Image.open('你的图片路径').convert('L')
width, height = img.size

# 初始化Turtle配置
t = turtle.Turtle()
t.speed(0)
turtle.tracer(0, 0)
t.penup()
# 调整起始位置让图片居中显示
t.goto(-width//2, height//2)

# 遍历每个像素点
for y in range(height):
    for x in range(width):
        gray_val = img.getpixel((x, y))
        # 灰度值低于127则落笔绘制,否则抬笔跳过
        if gray_val < 127:
            t.pendown()
        else:
            t.penup()
        t.goto(-width//2 + x, height//2 - y)
    turtle.update()

turtle.done()

方案2:直接在Turtle窗口显示图片(非逐笔绘制)

如果不需要模拟手绘过程,只是想在Turtle窗口展示图片,可使用形状注册功能(仅支持GIF格式,其他格式需先转GIF):

import turtle

# 将图片注册为Turtle可用的形状
turtle.register_shape('你的图片路径.gif')
t = turtle.Turtle()
t.shape('你的图片路径.gif')
turtle.done()

内容的提问来源于stack exchange,提问作者Aryan Mukhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 00:01:09