验证导致

2024-09-30 18:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

运行以下功能时:

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循环放入时。你知道吗


Tags: inpyselfforindextkinterlibline
1条回答
网友
1楼 · 发布于 2024-09-30 18:16:25

这意味着您试图在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)

相关问题 更多 >