2016-07-08 90 views
2

我有這樣的名單:元組索引超出相關curselection(Tkinter的)的誤差範圍

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 

我該如何防止這種情況發生?

回答

5

當您取消選擇該項目時,函數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

+0

'if len(b)> 0:''可以'如果b:' –

+0

非常感謝保羅 – AllanCampos

2

的@PaulComelius答案是正確的,我給了有用的筆記解決方案的變體:

首先要注意的是,只有Tkinter的1.160及更早版本會導致()的返回curselection列表是一個字符串列表而不是整數。這意味着你在seleção=INT鑄造一個整數值,以一個整數值,當運行沒用指令(a.curselection()[0]ativo=[a.get(INT() for i in a.curselection()]

其次,我寧願跑:

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

爲什麼?因爲這是Pythonic的方式。

第三次也是最後一次:運行import tkinter as tkfrom tkinter import *更好。

+0

謝謝m8,我做了修改 – AllanCampos