python - 国际象棋程序中的“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)
解决方案
看起来您收到此错误是因为您尝试访问的密钥player.moves
不存在,或者密钥的值为None
. 您可以通过执行健全性检查来解决此问题,以确保movelist
不是None
if movelist and self.newsquare in movelist:
self.square=(-10,-10)
self.newsquare=(-11,-11)
推荐阅读
- html - 如何获取每一行的值并计算小计
- javascript - 如何 - 每个连续动态创建的下拉列表都没有先前下拉列表的选定值
- java - 如何在使用 Scanner 读取输入文件时跳过几个字符?
- java - 如何跳过每行的前两个字符串?
- loopbackjs - 环回 ctx.instance 与 ctx.data
- c# - WPF - 绑定到 UserControl 的 PropDP - 在 ItemsControl 的 ItemTemplate 内
- python - 我想在 Django 或 sql 中为每种通知类型获取 10 个通知
- r - 通过将 i 与 i+1 进行比较,在循环中重新编码多个列
- android - getExternalMediaDirs() 在 Android 中已弃用
- java - 过滤器在 Android 上显示错误的项目