运行以下功能时:
def RestoreSelection(self, selectedItems):
self.RecvList.selection_clear(0,"end")
items = self.RecvList.get(0,"end")
for item in selectedItems:
for _i in items:
if item[:6] == _i[:6]:
index = items.index(item)
print index
self.RecvList.selection_set(index)
我收到此错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1437, in __call__
return self.func(*args)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 498, in callit
func(*args)
File "./pycan1.8.py", line 710, in RecvBtn_Click
self.RestoreSelection(selected)
File "./pycan1.8.py", line 443, in RestoreSelection
index = items.index(item)
ValueError: tuple.index(x): x not in tuple
不幸的是,错误消息并不十分清楚。有人可以解释这个错误信息是什么?是什么导致函数产生它。
这只发生在我将嵌套的for循环放入。
答案 0 :(得分:1)
这意味着您在items
元组中尝试查找的索引值在此元组中不存在。
>>> a = (1,2)
>>> a.index(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple
为了避免这种情况,你可以在你试图获取try\except
块的索引的地方包装行,例如:
def RestoreSelection(self, selectedItems):
self.RecvList.selection_clear(0,"end")
items = self.RecvList.get(0,"end")
for item in selectedItems:
for _i in items:
if item[:6] == _i[:6]:
try:
index = items.index(item)
except ValueError:
index = None #set default value here
print index
self.RecvList.selection_set(index)