尝试在乌龟窗口中书写时出错

时间:2019-12-10 16:50:45

标签: python

我收到此错误:

 Traceback (most recent call last):
File "c:\_Muh Stuff\IT\Learning\Python\Projet Hanoi\Main_Program.py", line 106, in <module>
    tab_res()
  File "c:\_Muh Stuff\IT\Learning\Python\Projet Hanoi\Partie_E.py", line 81, in tab_res
    write(elem, ": ", all_keys[i], "\n")
  File "<string>", line 8, in write
  File "C:\Users\Augustin\AppData\Local\Programs\Python\Python37-32\lib\turtle.py", line 3431, in write
    end = self._write(str(arg), align.lower(), font)
AttributeError: 'int' object has no attribute 'lower'

通过此代码:

`for i in range(0, len(all_keys)):
    if i == 6:
        break

    elem = dict1[all_keys[i]]

    print(elem, ": ", all_keys[i])

    turtle.write(elem, ": ", all_keys[i], "\n")

    del dict1[all_keys[i]]`

我只是不明白这个错误与乌龟有何关系

可能是由于末尾有“ \ n”吗?

1 个答案:

答案 0 :(得分:0)

write()不像print()

print()将使用您想要提供的任意数量的参数,并且每个参数将作为结果字符串的一部分打印,并自动用空格分隔。

另一方面,write()方法的签名如下:

 def write(self, arg, move=False, align="left", font=("Arial", 8, "normal")):

(来源:https://github.com/python/cpython/blob/master/Lib/turtle.py)。它以单个字符串作为第一个参数,而后续的位置参数具有不同的用途。通常,我们仅使用一个参数(要写入的字符串)来调用它。

我整理了一些测试数据以使您的代码正常工作,并将其组装起来以完成您想要的工作。

import turtle

my_turtle = turtle.Turtle()

# This fake dictionary contains some testing data.
# Everything is assumed to be a string.
dict1 = {"2": "Test",
         "random": "ASDF",
         ":-)": "qwerty",
         "8": "Cheese"}

# This is the order in which the lines will be processed
all_keys = ["8", "2", ":-)", "random"]

for i in range(0, len(all_keys)):
    if i == 6:
        break
    elem = dict1[all_keys[i]]

    # We will use this output string in both the print() and write() methods.
    output = elem + ": " + all_keys[i]

    print(output)
    my_turtle.write(output)

    # This will have the effect of moving the pen a little further down the screen,
    # to act a bit like "\n".
    my_turtle.penup()
    my_turtle.right(90)
    my_turtle.forward(20)
    my_turtle.left(90)
    my_turtle.pendown()

    del dict1[all_keys[i]]

my_turtle.done()

请注意,\n仅在我们write的每个字符串中有效,并且对后续字符串无效。因此,默认情况下,它们都将彼此覆盖。

在我的示例中,我通过手动将乌龟移动到下一行的开头来伪造它。另一种选择是建立一个大的输出字符串,其中包含由\n字符分隔的每一行,并将其全部写入(将起作用)。