我正在编写的代码的目的是让它能够从数组和相应的列表框中删除项目。我希望能够在列表框中没有突出显示任何项目时禁用删除项目的按钮(因为否则当您尝试按下按钮并且没有选择任何内容时它会返回错误,错误如下所示。)>>> Exception in Tkinter callback Traceback (most recent call last): File "G:\2Boys_stuff\lib\tkinter\__init__.py", line 1705, in __call__ return self.func(*args) File "H:/The Quiet Apocalypse/Tests/test_13.py", line 14, in remove LB = int(lb[0])IndexError: tuple index out of range我正在使用的代码如下:from tkinter import *import tkinter.messagebox as boxglobal listboxTF = Trueinventorylist1 = [("Item1","1.0"),("Item2","0.25"),("Item3","0.25")]def remove(): global TF global listbox lb = listbox.curselection() LB = int(lb[0]) del inventorylist1[LB] TF = False I(TF)def IR(): global windowir global listbox windowir = Tk() windowir.title( "IR" ) windowir.resizable( 0, 0 ) listframe = Frame( windowir ) listbox = Listbox( listframe ) for i in range(len(inventorylist1)): e = i+1 listbox.insert(e, inventorylist1[i]) Label_ir = Label( listframe, relief = "groove" ) Label_ir.pack( side = TOP ) btn_ir_1 = Button( listframe, text = "Remove", command = remove ) btn_ir_1.pack(side = BOTTOM ) listbox.pack(side = BOTTOM) listframe.pack(padx = 20, pady = 20) Label_ir.configure( text = "You are carrying: " ) windowir.mainloopdef I(Tf): global windowir if Tf == True: windowi = Tk() windowi.title( "I" ) windowi.resizable( 0, 0 ) IR() else: windowir.destroy() IR()I(TF)
1 回答

慕侠2389804
TA贡献1719条经验 获得超6个赞
只需将try and except错误添加并显示为弹出窗口即可
def remove():
global TF
global listbox
try:
lb = listbox.curselection()
LB = int(lb[0])
del inventorylist1[LB]
TF = False
I(TF)
except:
popup = Tk()
popup.wm_title("!")
label = Label(popup, text=" ERROR")
label.pack(side="top", fill="x", pady=10)
B1 = Button(popup, text="Okay", command = popup.destroy)
B1.pack()
popup.mainloop()
添加回答
举报
0/150
提交
取消