我一直在试图运行我的程序,但我每次做的时候,我得到这个:的Python KeyError异常,但没有字典
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\GURNHH\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "C:\Users\GURNHH\AppData\Local\Programs\Python\Python35-32\lib\turtle.py", line 686, in eventfun
fun()
File "C:/Users/GURNHH/OneDrive - Rugby School/ICT/Python/bored.py", line 22, in k1
badpos.remove((int(turtle.xcor()), int(turtle.ycor())))
KeyError: (0, 0)
我不知道它在这种情况下是指键错误,因为与许多其他人不同,我没有使用字典。 我的程序应该让乌龟在50次移动后回到中心,但不会在设置的badpos中计数0,0。我的程序是:
from turtle import Turtle, Screen
from math import *
from random import *
random = 0
"""def add():
random = random + 1
def check():
if random > 4:
random = 0"""
def k1():
global random
turtle.forward(10)
random = random + 1
if random > 5:
turtle.goto(0,0)
badpos.remove((int(turtle.xcor()), int(turtle.ycor())))
position = (int(turtle.xcor()), int(turtle.ycor()))
if position in badpos:
turtle.color("red")
screen.bye()
def k2():
turtle.left(90)
def k3():
turtle.right(90)
turtle = Turtle(shape="turtle")
badpos = set()
screen = Screen()
screen.setup(1200, 700)
screen.title("Turtle-Snaky Thing")
screen.onkey(k1, "Up")
screen.onkey(k2, "Left")
screen.onkey(k3, "Right")
screen.listen()
screen.mainloop()
[set](https://docs.python.org/3/library/stdtypes.html#set.remove)文档指出,如果你正在尝试的东西是'remove()'会引发'KeyError'删除不存在。 – JETM