如何停止这些乌龟错误,它们是什么意思?

时间:2019-08-26 18:49:02

标签: python python-3.x turtle-graphics

运行程序然后关闭Turtle窗口后,Python shell给我一个错误。

我正在尝试在pong的复制中沿屏幕中间绘制一条虚线。我对Python和Turtle很陌生。我也没有真正尝试修复它。

这是给我错误的代码:

import turtle as t

#creates screen & assigns it to 'screen'
screen = t.Screen()

#setiing up screen
screenSize = 500
screen.setup(screenSize, screenSize)

#variables
human = t.Turtle()
ai = t.Turtle()
border = t.Turtle()

spacing = 10

#assigns a path to paddle gif to 'paddle'
paddle = 'images/paddle.gif'

#adds 'paddle' to screen
screen.addshape(paddle)

#assigns 'paddle' to human & ai shape
human.shape(paddle)
ai.shape(paddle)

#penup
human.penup()
ai.penup()
border.penup()

#making border
border.hideturtle()
border.goto(0, 250)
border.pendown()
border.right(90)
x = 0

while x in range(int(screenSize/spacing)):

    border.forward(spacing)
    border.penup()
    border.forward(spacing)
    border.pendown()

这是错误:

  File "<pyshell#8>", line 3, in <module>
    border.forward(spacing)
  File "/usr/lib/python3.7/turtle.py", line 1637, in forward
    self._go(distance)
  File "/usr/lib/python3.7/turtle.py", line 1605, in _go
    self._goto(ende)
  File "/usr/lib/python3.7/turtle.py", line 3158, in _goto
    screen._pointlist(self.currentLineItem),
  File "/usr/lib/python3.7/turtle.py", line 755, in _pointlist
    cl = self.cv.coords(item)
  File "<string>", line 1, in coords
  File "/usr/lib/python3.7/tkinter/__init__.py", line 2469, in coords
    self.tk.call((self._w, 'coords') + args))]
_tkinter.TclError: invalid command name ".!canvas"error:

我希望它在中间划一条虚线,但是确实如此,但是当我关闭乌龟屏幕时,它给了我一个错误。

1 个答案:

答案 0 :(得分:0)

问题似乎是这实际上是一个无限循环:

 while x in range(int(screenSize/spacing)):

因此,当您关闭窗口时,将在循环中的命令之一中间中断它。问题是您使用的是while而不是for。这是我布置相同代码的方法:

from turtle import Screen, Turtle

# Declare constants
SCREEN_SIZE = 500
LINE_SPACING = 10
PADDLE_FILE = 'images/paddle.gif'

# Create screen & assign it
screen = Screen()

# Set up screen
screen.setup(SCREEN_SIZE, SCREEN_SIZE)

# Add 'paddle' to screen
screen.addshape(PADDLE_FILE)

# Initialize turtles
human = Turtle()
human.shape(PADDLE_FILE)
human.penup()

ai = Turtle()
ai.shape(PADDLE_FILE)
ai.penup()

border = Turtle()
border.hideturtle()
border.penup()

# Draw border
border.sety(250)
border.right(90)
border.pendown()

for _ in range(SCREEN_SIZE // (LINE_SPACING * 2)):
    border.forward(LINE_SPACING)
    border.penup()
    border.forward(LINE_SPACING)
    border.pendown()

screen.mainloop()