python - 当列表框中没有突出显示任何内容时,需要一种方法使 Tkinter 中的按钮变为禁用
问题描述
我正在编写的代码的目的是让它能够从数组和相应的列表框中删除项目。我希望能够在列表框中没有突出显示任何项目时禁用删除项目的按钮(因为否则当您尝试按下按钮并且没有选择任何内容时它会返回错误,错误如下所示。)
>>> 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 box
global listbox
TF = True
inventorylist1 = [("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.mainloop
def I(Tf):
global windowir
if Tf == True:
windowi = Tk()
windowi.title( "I" )
windowi.resizable( 0, 0 )
IR()
else:
windowir.destroy()
IR()
I(TF)
解决方案
只需将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()
推荐阅读
- ruby-on-rails - ActionController::UnknownFormat 在 CommentsController#index
- multithreading - GUI中的tIdHttp内部线程和IdTCPServer
- sql - 如何使用由日期时间值组成的 PIVOT 表
- javascript - 如何将值从 javascript 传递到控制器
- c# - 在运行时重定向汇编方法
- php - 从一个 SQL 数据库中提取并插入外部 SQL 数据库
- php - 我希望用户上传一张图片,然后给它一个标题,这样他们就可以给图片一个名字
- jquery - 在所有行中搜索特定数据属性。如果存在,隐藏其他行
- python - 带有嵌套字典的 JSON 内存数据库 (Python)
- spring - 用于复合 API 调用的 Spring Cloud Zuul?