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

Python Turtle库运行时安全编码警告及print语句未执行问题求助

问题解决方案

一、解决print("Hi")未显示的问题

你代码里的screen.exitonclick()是阻塞调用——程序会停在这一行,直到你手动关闭turtle窗口后,才会执行后面的print("Hi")。

两种处理方式:

  • 若想在窗口打开时就看到打印内容,把print("Hi")移到screen.exitonclick()之前:
    from turtle import Turtle, Screen
    
    timmy_the_turtle = Turtle()
    timmy_the_turtle.shape("turtle")
    
    print("Hi")  # 调整位置到这里
    
    screen = Screen()
    screen.exitonclick()
    
  • 若需要在窗口关闭后打印,只要关闭turtle窗口,终端里就会显示"Hi",只是之前你没留意这个执行顺序。

二、消除安全编码警告

这个警告是macOS系统针对Tkinter(turtle库基于Tkinter)的提示,不影响程序功能。要消除它,有两种方法:

  1. 修改代码添加环境变量:在代码最开头加入以下配置
    import os
    os.environ['NSApplicationSupportsSecureRestorableState'] = 'YES'
    os.environ['TK_SILENCE_DEPRECATION'] = '1'
    
    from turtle import Turtle, Screen
    
    # 后续原有代码不变
    timmy_the_turtle = Turtle()
    timmy_the_turtle.shape("turtle")
    print("Hi")
    screen = Screen()
    screen.exitonclick()
    
  2. 命令行运行时设置环境变量:执行脚本时添加环境变量参数
    NSApplicationSupportsSecureRestorableState=YES python your_script.py
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:22:13