Reputation: 21
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?
Upvotes: 2
Views: 2660
Reputation: 22724
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 *
.
Upvotes: 2
Reputation: 10916
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()]
Upvotes: 8