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

使用Turtle库多线程绘制谢尔宾斯基三角形遇RuntimeError问题求助

问题:使用turtle库多线程绘制谢尔宾斯基三角形报错RuntimeError: main thread is not in main loop

我尝试通过递归函数创建线程,基于turtle库(不可更换)同时绘制单个三角形来实现谢尔宾斯基三角形,但始终出现报错:RuntimeError: main thread is not in main loop。

最初的线程创建代码

这段代码本意是创建并启动绘制三角形的新线程,表面可运行:

def triangle_thread(x, y, size, invert=False):
    global turtles
    turtles.append(turtle.Turtle("turtle"))
    turtles[-1].speed("fastest")
    t = threading.Thread(target=partial(triangle, x, y, size, turtles[-1], invert=invert))
    t.daemon = True
    t.start()

修复尝试:将递归逻辑放入单独线程

我试过多种方法(包括队列操作)都无法实现同时绘制,最新尝试是把谢尔宾斯基三角形生成逻辑放在单独线程,让主线程运行turtle.mainloop,但该方法仅在最多4代迭代时有效,迭代次数更多时仍会报相同错误:

thread_sierpinski_recursive = threading.Thread(target=partial(sierpinski, -700, -500, 3, 1000))
thread_sierpinski_recursive.start()
turtle.mainloop()

尝试cdlane解决方案后的完整代码

import turtle
import math
from functools import partial
import threading

threads = []
turtle.speed("fastest")


def triangle(x, y, size, t, invert=False):
    y_offset = size*(math.sqrt(3)/2)
    t.hideturtle()
    t.penup()
    partial(t.goto, x, y)()
    t.pendown()
    partial(t.goto, x+size, y)()
    partial(t.goto, x+size/2, y-y_offset if invert else y+y_offset)()
    partial(t.goto, x, y)()


def inner_sierpinski(x, y, size, iteration, thread_in):
    global threads
    height = size * (math.sqrt(3) / 2)
    triangle(x + (size / 2), y + height, size, thread_in.Turtle, invert=True)
    if iteration > 3:
        for nx, ny in ((x, y), (x+(size/2), y+height), (x+size, y)):
            threads.append(threading.Thread(target=partial(sierpinski, x, y, iteration-1, size, is_first=False)))
            threads[-1].Turtle = turtle.Turtle("turtle", visible=False)
            threads[-1].Turtle.speed("fastest")
    elif iteration > 1:
        for nx, ny in ((x, y), (x+(size/2), y+height), (x+size, y)):
            sierpinski(nx, ny, iteration-1, size, is_first=False)


# 仅用于绘制最外层三角形,会调用inner_sierpinski,后者会三次调用本函数
def sierpinski(x, y, iterations, total_size, is_first=True):
    global threads
    if is_first:
        triangle(x, y, total_size, turtle)
        threading.main_thread().Turtle = turtle
        thread_out = threading.main_thread()
    else:
        thread_out = threads[-1]
    inner_sierpinski(x, y, total_size/2, iterations, thread_out)


sierpinski(-700, -500, 6, 1000)
for thread in threads:
    thread.start()
turtle.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:01:12