为什么Python turtle首次运行成功后后续运行窗口无响应?
问题原因
- 你使用的Spyder、Jupyter属于带常驻内核的交互式开发环境,首次运行turtle代码后,相关绘图资源、实例没有被正确释放,二次运行时新旧实例冲突就会触发窗口无响应
- 代码本身没有设置主循环退出逻辑,自定义的while死循环在你手动关闭窗口时无法正常终止,会导致内核状态异常最终崩溃
- 没有调用turtle内置的资源回收方法,残留的全局状态会持续影响后续代码运行
修复方案
你可以直接使用修改后的代码:
import turtle # 先清理之前残留的turtle资源,避免二次运行冲突 try: turtle.bye() except: pass wn=turtle.Screen() wn.title("Made by ") wn.bgcolor("black") wn.setup(width=800,height=600) wn.tracer(0) #Keeps the screen up #Paddle A paddle_a=turtle.Turtle() #object of turtle paddle_a.speed(0) #speed of animation paddle_a.shape("square") paddle_a.color("red") paddle_a.shapesize(stretch_wid=5, stretch_len=1) #default size is 20*20 paddle_a.penup() #not to draw lines paddle_a.goto(-350,0) #Paddle B paddle_b=turtle.Turtle() #object of turtle paddle_b.speed(0) #speed of animation paddle_b.shape("square") paddle_b.color("blue") paddle_b.shapesize(stretch_wid=5, stretch_len=1) #default size is 20*20 paddle_b.penup() #not to draw lines paddle_b.goto(350,0) #Ball ball=turtle.Turtle() #object of turtle ball.speed(0) #speed of animation ball.shape("circle") ball.color("white") ball.penup() #not to draw lines ball.goto(0,0) ball.dx=0.09 #moves by 2 pixels ball.dy=0.09 #Function def paddle_a_up(): y=paddle_a.ycor() #mentions the y coordinate y=y+20 paddle_a.sety(y) #set y coordinate to new y def paddle_a_down(): y=paddle_a.ycor() #mentions the y coordinate y=y-20 paddle_a.sety(y) #set y coordinate to new y def paddle_b_up(): y=paddle_b.ycor() #mentions the y coordinate y=y+20 paddle_b.sety(y) #set y coordinate to new y def paddle_b_down(): y=paddle_b.ycor() #mentions the y coordinate y=y-20 paddle_b.sety(y) #set y coordinate to new y # 定义窗口关闭时的处理逻辑,终止主循环 def close_window(): global running running = False wn.bye() #Keyboard binding wn.listen() #listen keyboard input wn.onkeypress(paddle_a_up,'w') wn.onkeypress(paddle_a_down,'s') wn.onkeypress(paddle_b_up,"Up") wn.onkeypress(paddle_b_down,"Down") # 绑定窗口关闭事件 wn.getcanvas().winfo_toplevel().protocol("WM_DELETE_WINDOW", close_window) #Main loop running=True while running: try: wn.update() #updates the screen #movement the ball ball.setx(ball.xcor()+ball.dx) ball.sety(ball.ycor()+ball.dy) # 补充边界碰撞判断,避免球飞出屏幕 if ball.ycor() > 290 or ball.ycor() < -290: ball.dy *= -1 if ball.xcor() > 390 or ball.xcor() < -390: ball.goto(0,0) ball.dx *= -1 except turtle.Terminator: # 捕获turtle终止异常,避免内核崩溃 running = False break
注意事项
- 如果修改代码后还是偶发无响应,在运行前执行
%reset -f清空当前内核的变量即可 - 频繁测试turtle类图形代码时,更推荐直接用原生Python解释器运行py文件,交互式环境的常驻内核天生容易和这类带全局状态的图形库产生冲突
内容的提问来源于stack exchange,提问作者Uncle Iroh
相关产品推荐
相关产品推荐

