如何无误地从列表框中选择?

2 投票
1 回答
35 浏览
提问于 2025-04-12 07:23

我想从一个列表框中选择一个选项,然后用这个选项去获取其他数据,这些数据会被放到另一个列表框中供我选择。当我选择第一个列表框的选项时,一切都很顺利,没有任何错误。第二个列表框在我选择第一个列表框的选项后也能成功更新,显示新的列表。但是,当我选择第二个列表框的选项时,虽然大部分功能正常,但却出现了一个错误。

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()

这段代码确实能实现我想要的功能,但我对这个错误感到不太舒服。错误信息是:

文件 "C:\Users\a\Desktop\emma\PROJECT\index.py",第 685 行,在 get_selected 中 index = int(biblelist.curselection()[0]) ~~~~~~~~~~~~~~~~~~~~~~~~^^^ IndexError: tuple index out of range

我尝试了很多方法来解决这个错误,但还是没能成功。我真的需要帮助,我对Python编程还很陌生。

1 个回答

1

你遇到的这个错误(IndexError: tuple index out of range)是因为你试图访问一个空的元组中的某个位置。简单来说,就是当你在列表框中没有选中任何项目时,curselection()返回的是一个空的元组。这种情况下,你就不能去访问它的索引了。为了避免这个问题,你应该在尝试访问索引之前,先检查一下是否有选中的项目。

比如说,你可以这样写:

def get_selected(e):
    global book_selected
    if biblelist.curselection():  # 这里加上检查,处理错误
        index = int(biblelist.curselection()[0])

再比如:

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

撰写回答