【问题标题】:How can you trap TurtleGraphicsError with a 'try' statement如何用“try”语句捕获 TurtleGraphicsError
【发布时间】:2014-02-14 17:23:04
【问题描述】:

如果您在 Python 的 Turtle Graphics 中输入了无法识别的颜色,系统会返回给您,例如:

Traceback (most recent call last):
  File "C:\Python33\turtle\ex21-starafterstar.py", line 18, in <module>
    color(outline,fillcol)      # Set pen and fill colors
  File "<string>", line 1, in color
  File "C:\Python33\lib\turtle.py", line 2208, in color
    pcolor = self._colorstr(pcolor)
  File "C:\Python33\lib\turtle.py", line 2688, in _colorstr
    return self.screen._colorstr(args)
  File "C:\Python33\lib\turtle.py", line 1150, in _colorstr
    raise TurtleGraphicsError("bad color string: %s" % str(color))
turtle.TurtleGraphicsError: bad color string: yucky brown

由此可以推断,在 'try 语句中捕获此类错误的方法是编写代码:

try:
    outline = input("Enter the outline color  > ")
    pencolor(outline)
    break
except TurtleGraphicsError:
    print("Sorry. I don't recognise that color.")

但这不起作用。它会产生以下错误:

Traceback (most recent call last):
  File "C:/Python33/turtle/ex28-star5coloredtry.py", line 17, in <module>
    except TurtleGraphicsError:
NameError: name 'TurtleGraphicsError' is not defined

因此,我的问题是,Turtle Graphics 错误的错误类的名称是什么?

【问题讨论】:

    标签: exception graphics exception-handling turtle-graphics


    【解决方案1】:

    如错误消息所述,名称TurtleGraphicsError 未在该范围内定义。它在turtle 包中定义。您可以像这样导入它:

    from turtle import TurtleGraphicsError
    

    或使用它的限定名称

    import turtle
    try:
        ...
    except turtle.TurtleGraphicsError:
        print(...)
    

    【讨论】:

    • 对不起,shx2,但您的解决方案都不起作用!您是否真的尝试过并测试过这些?
    • 等一下。没关系。您必须实际导入海龟而不是“从海龟导入 TurtleGraphicsError”。谢谢。
    • @JohnofYork 我想当然地认为你已经有了import turtle 行。编辑了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2015-11-22
    • 2019-12-17
    • 1970-01-01
    相关资源
    最近更新 更多