【问题标题】:multiple lists with the same callback function lead to IndexError具有相同回调函数的多个列表导致 IndexError
【发布时间】:2023-01-30 22:18:10
【问题描述】:

我将 tkinter 用于 GUI,并创建了两个列表:

# widgets     
create_list(win, 20, 20, ["Test", "Apfel", "Birne"])     
create_list(win, 220, 20, ["Alpha", "Beta", "Gamma", "Delta"])

其中 create_list 是一个函数:

def create_list(win, xx, yy, items=\[\]):
    lb = Listbox(win)
    i = 1
    for item in items:
        lb.insert(i, item)
        i += 1    
    lb.bind('<<ListboxSelect>>', on_select)
    lb.place(x=xx, y=yy) 

到目前为止没有什么特别的。 我有一个on_select用作两个列表的选择更改的回调。

def on_select(event):         
    w = event.widget         
    index = int(w.curselection()[0])         
    value = w.get(index)         
    print(f'You selected item {index}: {value}')`

它按预期工作,打印我选择的项目。 但是,如果我单击第二个列表中的一个项目(反之亦然),我会收到错误消息:

Tkinter 回调 Traceback 中的异常(最后一次调用):
文件“/usr/lib/python3.8/tkinter/在里面.py”,第 1892 行,在称呼返回 self.func(*args) 文件 “/home/userx/projects/python/modules/ws_list.py”,第 8 行,on_select index = int(w.curselection()[0]) IndexError: 元组索引超出范围

如果我然后选择同一列表中的另一个项目,问题就消失了。 我如何解决这个问题?每个列表都需要不同的回调函数吗?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    根据this answer,如果从列表框中删除选择,将触发&lt;&lt;ListboxSelect&gt;&gt;事件,这就是在列表之间切换时发生的情况。这将导致一个空的curselection,这就是导致您出错的原因。为避免这种情况,请在使用前检查选择是否为空。

    def on_select(event):         
        w = event.widget
        selection = w.curselection()
        if selection:
            index = int(selection[0])         
            value = w.get(index)         
            print(f'You selected item {index}: {value}')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      相关资源
      最近更新 更多