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

Python Turtle遇Terminator异常:多次实例化窗口失败求助

问题分析与解决方案

问题根源

你的代码触发Terminator异常,是因为turtle.Screen().exitonclick()的行为不止关闭窗口——它会调用Tkinter的destroy()方法,终止整个Tkinter主事件循环,同时清理turtle模块的全局内部状态。这意味着后续即便创建新的Turtle_Looping实例,turtle模块也无法再初始化新的Screen或Turtle对象,因为底层的Tkinter环境已经被彻底销毁。

修复方案(推荐)

复用单个Screen实例,每次循环仅创建新的Turtle对象,执行完成后清理当前Turtle而非关闭整个屏幕。这种方式既能保留多次运行的逻辑,又不会破坏Tkinter的全局环境:

import numpy as np
from turtle import Turtle, Screen

class Turtle_Looping():
    def __init__(self, screen):
        self.screen = screen
        self.turt = Turtle()
        self.angles = [20,45,65,80,90,95]
        self.colors = ["red","blue","red","black","red","blue"]
        
    def Basic_Move(self):
        self.screen.tracer(0)
        for i in range(len(self.angles)):
            self.turt.pendown()
            self.turt.color(self.colors[i])
            self.turt.right(self.angles[i])
            self.turt.forward(150)
            self.turt.penup()
            self.screen.update()
        
        # 点击屏幕后清理当前海龟,准备下一次运行
        def handle_click(x, y):
            self.turt.clear()
            self.turt.hideturtle()
            self.screen.onscreenclick(None)  # 解绑当前点击事件
        
        self.screen.onscreenclick(handle_click)
        self.screen.mainloop()  # 启动事件循环等待点击

def Call_Turtle_Looping():
    # 只创建一次Screen实例
    main_screen = Screen()
    for i in range(4):       
        print(f"we are on run #{i}")
        inst = Turtle_Looping(main_screen)
        inst.Basic_Move()
        
Call_Turtle_Looping()

另一种可选方案(重置全局状态)

如果坚持要每次关闭窗口后重新打开,可以通过重载turtle模块重置全局状态,但这种方法稳定性稍差:

import numpy as np
import importlib
from turtle import Turtle, Screen

class Turtle_Looping():
    def __init__(self):
        self.turt = Turtle()
        self.screen = Screen()
        self.angles = [20,45,65,80,90,95]
        self.colors = ["red","blue","red","black","red","blue"]
        
    def Basic_Move(self):
        self.screen.tracer(0)
        for i in range(len(self.angles)):
            self.turt.pendown()
            self.turt.color(self.colors[i])
            self.turt.right(self.angles[i])
            self.turt.forward(150)
            self.turt.penup()
            self.screen.update()

        self.screen.exitonclick()
        # 清理当前实例引用
        del self.turt
        del self.screen

def Call_Turtle_Looping():
    global Turtle, Screen
    for i in range(4):       
        print(f"we are on run #{i}")
        # 重载turtle模块重置全局状态
        import turtle
        importlib.reload(turtle)
        Turtle = turtle.Turtle
        Screen = turtle.Screen
        inst = Turtle_Looping()
        inst.Basic_Move()
        
Call_Turtle_Looping()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 01:10:14