【问题标题】:NameError: name 'turtle' is not defined running turtle.Screen()NameError: name \'turtle\' 未定义运行 turtle.Screen()
【发布时间】:2023-02-17 04:43:53
【问题描述】:

这是我的代码:

window=turtle.Screen()
window.title("Pong")
window.bgcolor("black")
window.setup(width=800,height=600)
window.tracer(0)

运行程序时出现此错误:

 File "C:\Users\Aditya\PycharmProjects\pythonProject\main.py", line 6, in <module>
    window=turtle.Screen()
NameError: name 'turtle' is not defined

有什么问题,我该如何解决?

【问题讨论】:

  • 您是否导入了带 import turtle 行的 turtle 模块?
  • 很抱歉提出这样一个愚蠢的问题。我想不通

标签: python turtle-graphics python-turtle


【解决方案1】:

我想你忘了导入 turtle

import turtle
window=turtle.Screen()
window.title("Pong")
window.bgcolor("black")
window.setup(width=800,height=600)
window.tracer(0)

【讨论】:

    【解决方案2】:

    在调用其中的子函数之前,您需要导入模块。在您的情况下,您需要 turtle 模块。

    import turtle
    window=turtle.Screen()
    window.title("Pong")
    window.bgcolor("black")
    window.setup(width=800,height=600)
    window.tracer(0)
    

    但是,如果你添加了import turtle这一行,并遇到下面的错误:

    File "/usr/lib/python3.8/turtle.py", line 107, in <module>
    import tkinter as TK 
    ModuleNotFoundError: No module named 'tkinter'
    

    你可以参考这个帖子:here

    【讨论】:

      【解决方案3】:

      您是否导入了 Turtle 模块? 如果你没有,试试这个:

      from turtle import *
      

      然后剩下的代码

      【讨论】:

      • 这不会使 OP 的代码工作,因为它将 turtle 中的所有内容导入当前命名空间。
      • 即使这确实有效,用 100 多个海龟函数污染 globals() 命名空间也是不好的做法,通常会导致大量的混乱和错误。
      猜你喜欢
      • 2022-11-21
      • 2022-09-23
      • 2022-11-25
      • 2016-05-24
      • 1970-01-01
      • 2023-01-17
      • 2018-09-11
      • 2020-11-15
      • 1970-01-01
      相关资源
      最近更新 更多