为了账号安全,请及时绑定邮箱和手机立即绑定

当列表框中没有突出显示任何内容时,需要一种方法使 Tkinter 中的按钮变为禁用

当列表框中没有突出显示任何内容时,需要一种方法使 Tkinter 中的按钮变为禁用

隔江千里 2022-06-28 15:33:17
我正在编写的代码的目的是让它能够从数组和相应的列表框中删除项目。我希望能够在列表框中没有突出显示任何项目时禁用删除项目的按钮(因为否则当您尝试按下按钮并且没有选择任何内容时它会返回错误,错误如下所示。)>>> 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()


查看完整回答
反对 回复 2022-06-28
  • 1 回答
  • 0 关注
  • 136 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号