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

双击Python脚本后Turtle窗口自动关闭问题求助

解决Turtle脚本双击运行后窗口自动关闭的问题

你的脚本存在两个问题导致双击运行时窗口自动关闭:

  1. 输入的半径是字符串类型,未转换为数值,导致后续数学计算抛出异常,程序提前终止
  2. turtle.mainloop()的位置不合理,即使计算正常,程序执行完后也会直接退出

修复步骤及代码修改:

  1. 将输入的半径转换为浮点数,避免类型错误
  2. 把turtle.mainloop()移到脚本末尾,确保绘图完成后进入事件循环,保持窗口打开

修改后的完整代码:

import math
import turtle

def arc(t, radius, angle):
    arc_length = 2 * math.pi * radius * angle / 360
    n = int(arc_length / 3) + 1
    step_length = arc_length / n
    step_angle = float(angle) / n
    polyline(t, n, step_length, step_angle)

def polyline(t, n, length, angle):
    for i in range(n):
        t.fd(length) 
        t.lt(angle)

def circle(t, r):
    arc(t, r, 360)

# 将输入转换为浮点数,确保计算正常
radius = float(input("Enter the radius of the circle to be printed: "))
bob = turtle.Turtle()
circle(bob, radius)

# 启动Turtle事件循环,保持窗口打开直到用户手动关闭
turtle.mainloop()

额外说明:

如果在某些环境下turtle.mainloop()仍无法保持窗口打开,可以在mainloop()之后添加一行阻塞代码,让程序等待用户输入再结束:

input("Press Enter to close the window...")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 02:26:06