尝试在龟风中写入时出错

2024-06-17 13:12:48 发布

您现在位置: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”


Tags: inpy错误lineitkeysallfile
1条回答
网友
1楼 · 发布于 2024-06-17 13:12:48

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仅在每个字符串wewrite中有效,对后续字符串没有影响。因此,默认情况下,它们都将被写在彼此的顶部

在我的示例中,我通过手动将海龟移动到下一行的开头来伪造它。另一种方法是构建一个大的输出字符串,其中包含由\n字符分隔的每一行,并一次编写所有这些内容(这将起作用)

相关问题 更多 >