turtle.TurtleGraphicsError 没有注册?

turtle.TurtleGraphicsError not registering?

我有这个代码运行:

import random
import turtle 

turtle.speed(0)
def jump(x,y):
    turtle.penup()
    turtle.goto(x,y)
    turtle.pendown()
#end def

def random_walk(n_steps):
    turtle.goto(0,0)
    for i in range(n_steps):
        leftright = random.randint(0,10)
        if leftright<5:
            turtle.left(random.randint(0,359))
            turtle.forward(random.randint(8,12))       
        elif 5<leftright:
            turtle.right(random.randint(0,359))
            turtle.forward(random.randint(8,12))
    #end for
#end def
step = int(input("How far would you like your turtle to move?"))

while True:
    try:
        color = input("And what color would you like your turtle to be?")
        break
    except turtle.TurtleGraphicsError:
        print('Oops! i dont recognize taht color, try another!')


turtle.pencolor(color)
random_walk(step)

我的计划是让代码在执行无效颜色字符串时停止发生错误,但是 shell 仍然 returns 此错误:

And what color would you like your turtle to be?redf
Traceback (most recent call last):
  File "/Users/sgomena/Desktop/122/project 5/project5d.py", line 35, in <module>
    turtle.pencolor(color)
  File "<string>", line 1, in pencolor
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/turtle.py", line 2252, in pencolor
    color = self._colorstr(args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/turtle.py", line 2696, in _colorstr
    return self.screen._colorstr(args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/turtle.py", line 1158, in _colorstr
    raise TurtleGraphicsError("bad color string: %s" % str(color))
turtle.TurtleGraphicsError: bad color string: redf
>>> 

我已经调查过了,如果代码 运行 正确的话,我似乎应该得到一个不同的错误。 在此先感谢您的帮助!

非常简单!您需要在 try/except 块中插入设置乌龟笔颜色的行 (turtle.pencolor(color))。

否则,向turtle.pencolor()方法传递一个无效的color,但有没有try/except 处理这个的块。

step =  int(turtle.numinput("Choose a distanc", "How far would you like your turtle to move?", minval=0, maxval=10))
while True:
    try:
        print(turtle.pencolor())
        color = turtle.textinput("Choose a color", "What color would you like your turtle to be?")
        turtle.pencolor(color)   # Must be inside the try/except block    
        break
    except turtle.TurtleGraphicsError:
        print('Oops! i dont recognize taht color, try another!')

我也推荐使用海龟输入法(textinput()numinput())弹出对话框window输入字符串或浮点数(见上面的代码)。如需更多信息,请访问 documentation site.