简体   繁体   English

Python try-except名称错误

[英]Python try-except Name Error

I am making a clock type program in Python which has the option for formatting. 我正在用Python制作一个时钟类型程序,该程序具有格式化选项。 I've got a function where the background colour is assigned by a variable, but I want to make the program user-friendly. 我有一个函数,其中背景色是由变量分配的,但是我想使程序易于使用。 When the variable for the bg colour is a string like "black", it returns this: 当bg color的变量是“ black”之类的字符串时,它将返回以下内容:

      File "C:\Python27\lib\lib-tk\turtle.py", line 1105, in _colorstr
        raise TurtleGraphicsError("bad color string: %s" % str(color))
    TurtleGraphicsError: bad color string: black

And so I added the try except code which is meant to catch the TurtleGraphicsError error. 因此,我添加了try try代码,该代码旨在捕获TurtleGraphicsError错误。 However, when I run the code, this happens: 但是,当我运行代码时,会发生这种情况:

    except (TurtleGraphicsError):
NameError: name 'TurtleGraphicsError' is not defined

I've tried with and without brackets. 我已经尝试过使用方括号或不使用方括号。 Any idea why this is happening? 知道为什么会这样吗?

Python 2.7.12, Windows 8.1 Used imports are: Python 2.7.12,Windows 8.1使用的导入为:

from datetime import datetime
from calendar import day_name
from time import sleep
import turtle
import os

The error message says it correctly, the name TurtleGraphicsError is not defined in that scope. 错误消息正确地说明了该名称,未在该范围内定义名称TurtleGraphicsError。 It is defined inside the turtle package (hence it tells you turtle.TurtleGraphicsError). 它是在turtle包内定义的(因此它告诉您turtle.TurtleGraphicsError)。 You can either import it like: 您可以像这样导入它:

from turtle import TurtleGraphicsError

or use it's actual name 或使用它的真实名称

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM