All*_*pos 2 python listbox tkinter
我有这个清单:
lista=Listbox(root,selectmode=MULTIPLE)
lista.grid(column=0,row=1)
lista.config(width=40, height=4)
lista.bind('<<ListboxSelect>>',selecionado)
Run Code Online (Sandbox Code Playgroud)
附加到此功能:
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()]
Run Code Online (Sandbox Code Playgroud)
但是,如果我选择了某些内容然后取消选择,我会收到此错误:
seleção=int(a.curselection()[0])
IndexError: tuple index out of rangeenter code here
Run Code Online (Sandbox Code Playgroud)
我怎样才能防止这种情况发生?
取消选择该项时,函数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()]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1487 次 |
| 最近记录: |