简体   繁体   中英

tuple index out of range error related to curselection (tkinter)

I have this list:

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

Attached to this function:

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

But if I select something and then deselect, I get this error:

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

How can I prevent this from happening?

When you deselect the item, the function curselection() returns an empty tuple. When you try to access element [0] on an empty tuple you get an index out of range error. The solution is to test for this condition.

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 .

The @PaulComelius answer is correct, I am giving a variant of the solution with useful notes:

First note is that only Tkinter 1.160 and earlier versions causes the list returned by curselection() to be a list of strings instead of integers. This means you are running useless instructions when casting an integer value to an integer value in seleção= int( a.curselection()[0] ) and ativo=[a.get( int( i ) ) for i in a.curselection()]

Secondly, I would prefer to run:

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

Why? Because this is the Pythonic way.

Thirdly and last: Better to run import tkinter as tk than from tkinter import * .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM