首页 > 解决方案 > 国际象棋程序中的“TypeError:'NoneType'类型的参数不可迭代”

问题描述

我正在编写一个国际象棋程序,在我的代码中,我一直在我的函数中遇到这个错误。这发生在倒数第三行。完整的追溯是:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\jacob\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:\Users\jacob\Desktop\chess2.py", line 96, in <lambda>
    buttons=(tk.Button(self.boardframe, padx=10,  text=self.placepieces(pos), borderwidth=0, bg=colour,  relief="solid", font=self.piecefont, command=lambda position=pos: self.movepiece(position)  ))
  File "C:\Users\jacob\Desktop\chess2.py", line 73, in movepiece
    if self.newsquare in movelist:
TypeError: argument of type 'NoneType' is not iterable

定义按钮的位置:

    def drawboard(self):

        x=0
        y=0
        for column in range(self.n):
            self.changecolours()
            x=x+1
            y=0
            for row in range(self.n):
                y=y+1
                colour = self.colours[self.colourindex]
                pos=(x,9-y)
                buttons=(tk.Button(self.boardframe, padx=10,  text=self.placepieces(pos), borderwidth=0, bg=colour,  relief="solid", font=self.piecefont, command=lambda position=pos: self.movepiece(position)  ))
                buttons.grid(column=(x-1), row=(y-1), sticky="W"+"E"+"N"+"S" )
                self.changecolours()
    def movepiece(self, squareposition):
        player=Game().player
        turn=Game().turn
        if self.square==(-10,-10):
            self.square=squareposition
            if self.square in player.position.values()==True:
                for key in player.position:
                    pieceposition=player.position.get(key)
                    if self.square==pieceposition:
                        self.piece=key
                        break
                    else:
                        pass
            else:
                self.gamelabel.config(text="Error no " +str(turn)+" piece on this square please try again")
                self.square==(-10,-10)

        else:
            self.newsquare=squareposition
            if self.newsquare==self.square:
                self.square=(-10,-10)
                self.newsquare=(-11,-11)
                self.gamelabel.config(text=str(turn)+" to move")
            else:
                movelist=player.moves.get(self.piece)
                if self.newsquare in movelist:
                   self.square=(-10,-10)
                   self.newsquare=(-11,-11)

标签: pythonpython-3.xfunction

解决方案


看起来您收到此错误是因为您尝试访问的密钥player.moves不存在,或者密钥的值为None. 您可以通过执行健全性检查来解决此问题,以确保movelist不是None

if movelist and self.newsquare in movelist:
   self.square=(-10,-10)
   self.newsquare=(-11,-11)

推荐阅读