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

运行Python turtle绘图代码输入参数后窗口无响应消失如何解决

问题根源

你代码中的嵌套while循环存在死逻辑:
内层while x<400的循环体中没有任何修改x值的逻辑,只要进入这个循环(输入正方形数量≥2时,初始x=65<400就会触发进入),程序会永久卡在内层循环中,永远执行不到后面的turtle.update()和turtle.mainloop(),所以绘图窗口无响应、最后直接崩溃退出。

修复方案

删掉多余的内层while x<400判断即可,修复后代码如下:

import turtle
from random import randint
turtle.tracer(0)
turtle.bgcolor('black')
turtle.colormode(255) # 把colormode设置移到循环外,无需重复设置提升效率

# 读取用户输入的正方形数量
f=int(input("How many squares do you want?"))
i=1
x=65

# 绘制指定数量的正方形
while i <= f: # 条件改为<=避免少画第一个正方形
    r=randint(0,255)
    g=randint(0,255)
    b=randint(0,255)
    turtle.pencolor(r,g,b)
    # 绘制正方形的重复逻辑用for循环简化
    for _ in range(4):
        turtle.bk(x)
        turtle.rt(90)
    turtle.up()
    turtle.rt(9)
    turtle.down()
    x=x*1.05
    i=i+1

turtle.update()
turtle.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:57:03