【问题标题】:tuple index out of range error related to curselection (tkinter)与curselection(tkinter)相关的元组索引超出范围错误
【发布时间】:2016-11-10 13:20:07
【问题描述】:

我有这个清单:

lista=Listbox(root,selectmode=MULTIPLE)
lista.grid(column=0,row=1)                              
lista.config(width=40, height=4)                        
lista.bind('<<ListboxSelect>>',selecionado) 

附加到这个函数:

def selecionado(evt):
    global ativo
    a=evt.widget
    seleção=int(a.curselection()[0])    
    sel_text=a.get(seleção)
    ativo=[a.get(int(i)) for i in a.curselection()]

但是如果我选择了一些东西然后取消选择,我会得到这个错误:

    seleção=int(a.curselection()[0])
IndexError: tuple index out of rangeenter code here

如何防止这种情况发生?

【问题讨论】:

    标签: python tkinter listbox


    【解决方案1】:

    当您取消选择项目时,函数 curselection() 返回一个空元组。当您尝试访问空元组上的元素 [0] 时,您会收到索引超出范围错误。解决方案是测试这种情况。

    def selecionado(evt):
        global ativo
        a=evt.widget
        b=a.curselection()
        if len(b) > 0:
            seleção=int(a.curselection()[0])    
            sel_text=a.get(seleção)
            ativo=[a.get(int(i)) for i in a.curselection()]
    

    TkInter Listbox docs.

    【讨论】:

    • if len(b) &gt; 0: 可能是if b:
    【解决方案2】:

    @PaulComelius 的答案是正确的,我给出了解决方案的变体,并附有有用的注释:

    首先要注意的是,只有 Tkinter 1.160 和更早的版本会导致 curselection() 返回的列表是字符串列表而不是整数。这意味着在将整数值转换为 seleção=int( a.curselection()[0]) 和 @987654323 中的整数值时,您正在运行 useless 指令@int( i )) for i in a.curselection()]

    其次,我更喜欢运行:

      def selecionado(evt):
            # ....
            a=evt.widget
            if(a.curselection()):
               seleção = a.curselection()[0]  
            # ...
    

    为什么?因为这是 Pythonic 的方式。

    第三个也是最后一个:运行import tkinter as tk 比运行from tkinter import * 更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      相关资源
      最近更新 更多