如何从列表框中选择而不出现错误?

问题描述 投票:0回答:1

我想从列表框中进行选择,并使用所选的值来检索其他数据,这些数据也将插入到另一个列表框中以供选择。选择第一个列表框时,它可以成功运行,没有任何错误。选择第一个列表框时,第二个列表框也会更新为新列表。当选择第二个列表框时,问题就出现了,除了随之而来的错误异常之外,预期的一切都工作正常。

from tkinter import *
root= Tk()
books = ['Genesis', 'Exodus', 'Leviticus']
chapter = [1,2,3,4,5]
biblelist = Listbox(root)
biblelist.pack(side=LEFT)
biblelist.insert(END, 0)

chapter = Listbox(root)
chapters.pack(side=LEFT)

def get_selected(e):
    global book_selected
    index = int(biblelist.curselection()[0])
    value=biblelist.get(index)
    book_selected = '%s' %(value)
    if book_selected == books[0]
        for x in chapter:
            chapters.insert(END, x)


def get_selected_chapter(event):
    ind = int(chapters.curselection()[0])
    val=chapters.get(ind)
    chapter_selected = '%s' %(val)
    print(book_selected + chapter_selected)

biblelist.bind('<<ListboxSelect>>',get_selected)
chapters.bind('<<ListboxSelect>>', get_selected_chapter)
root.mainloop()

代码真实地给了我我想要的东西,但我对这个错误感到不舒服。 这是错误:

File "C:\Users\a\Desktop\emma\PROJECT\index.py", line 685, in get_selected index = int(biblelist.curselection()[0]) ~~~~~~~~~~~~~~~~~~~~~~~~^^^ IndexError: tuple index out of range

我尝试了各种方法来消除错误,但仍然失败。我真的需要帮助。我也是 python 编程新手。

python
1个回答
0
投票

您遇到的错误(IndexError:元组索引超出范围)是因为您尝试访问空元组的索引而发生的。当 curselection() 返回空元组时会发生这种情况,因为列表框中没有选择任何项目。要处理这个问题,您应该在尝试访问其索引之前首先检查是否有选择。

例如。 def get_selected(e): 全球图书精选 if biblelist.curselection(): # 添加此端口用于错误处理 索引 = int(biblelist.curselection()[0])

def get_selected_chapter(事件): if Chapters.curselection(): # 错误处理 ind = int(chapters.curselection()[0])

© www.soinside.com 2019 - 2024. All rights reserved.