我一直在試圖運行我的程序,但我每次做的時候,我得到這個:的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