簡體   English   中英

為什么我得到 KeyError: 0

[英]Why am I getting KeyError: 0

我正在嘗試編寫康威的生命游戲。 據我所知,程序應該是完整的,但是當我運行它時,我得到 KeyError:0,據我了解,這意味着引用了不存在的字典鍵。 字典 (cell_dict) 包含 20x20 網格的 tkinter 按鈕,這些按鈕形成死/活單元格。

這是整個代碼:

#imports
import tkinter
import random

#functions
def step(): #updates the status of each cell
    for i in range(0,20): # runs through each cell to check the number of living neighbors
        for j in range(0,20):

            cell = cell_dict[i][j] #key error happens here
            pop = 0

            for n in range(-1,2): #checks each neighbor and tracks the number of alive ones
                for m in range(-1,2):
                    if i+n in range(0,20) and j+m in range(0,20):
                        if n != 0 or m != 0:
                            cell_neighbor = cell_dict[i+n][j+m]
                            if cell_neighbor['bg'] == "yellow":
                                pop += 1

            if cell['bg'] == "yellow" and (pop == 2 or pop == 3): #primes the new status for the cell
                cell['fg'] = "yellow"
            elif cell['bg'] == "black" and pop == 3:
                cell['fg'] = "yellow"
            else:
                cell['fg'] = "black"

    for i in range(0,20): #updates the status of each cell
        for j in range(0,20):
            cell = cell_dict[i][j]
            if cell['fg'] == "black":
                cell['bg'] = "black"
            elif cell['fg'] == "yellow":
                cell['bg'] = "yellow"

    window.after(1000,step) #repeats the process every second

#gui
window = tkinter.Tk()

cell_dict = {} #primes the dictionary

for i in range(0,400): #creates all the cells
    cell = tkinter.Button(fg = "white", bg = "white", height = 1, width = 2)

    r = random.randrange(0,2) #randomly determines if the cell will be initially dead or alive

    if r == 0:
        cell['bg'] = "black" #dead
    elif r == 1:
        cell['bg'] = "yellow" #alive

    cell.grid(row = int(i/20)%20, column = i%20) #packs the cell into the grid

    cell_dict[(int(i/20)%20,i%20)] = cell #stores the cell in the dictionary

#mainloop
step()
window.mainloop()

我注意到一旦關鍵錯誤彈出,i = 399 並且 j 是未定義的。 因此,代碼似乎以某種方式跳過了“for i in range(0,2): for j in range(0,20):”。 我是編碼新手,所以我不確定我哪里出錯了。

看起來您將單元格位置存儲為兩個整數的元組。 所以你應該用它而不是integer來處理cell_dict。

使用cell_dict[(i, j)]而不是cell_dict[i][j]

你沒有包括回溯,所以這只是一個有根據的猜測,但我懷疑你的問題寫得更清楚,如下所示:

cell_dict = {}
for i in range(0,400):
    cell_dict[(int(i/20)%20,i%20)] = None

print(cell_dict)
for i in range(0,20):
    for j in range(0,20):
    cell = cell_dict[i][j]  # key error happens here

事實上,你確實有你的關鍵錯誤。

您的鍵是cell_dict[(x, y)] -> cell ,但您的意思是cell_dict[x][y] -> cell

您可以通過多種方式解決此問題,在循環中分配 dicts,使用如下setdefaultcollections.defaultdict等。

    cell_dict.setdefault(int(i/20)%20, {})[i%20] = None

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM