Python 如何在Tkinter中使用curselection选择“不说话”
我有一个使用Python 如何在Tkinter中使用curselection选择“不说话”,python,tkinter,Python,Tkinter,我有一个使用Listbox.curselection()的代码: 当列表框中未选择任何内容时,我希望引发一个错误窗口 如有任何反馈,将不胜感激。 谢谢 我不是100%确定问题出在哪里。如果未选择任何项目,则self.\u Listbox.curselection()应返回emtpy列表。由于您随后获取索引0,因此它应该抛出一个索引器 演示代码: from Tkinter import * master = Tk() listbox = Listbox(master) listbox.pack
Listbox.curselection()
的代码:
当列表框中未选择任何内容时,我希望引发一个错误窗口
如有任何反馈,将不胜感激。
谢谢 我不是100%确定问题出在哪里。如果未选择任何项目,则
self.\u Listbox.curselection()
应返回emtpy列表。由于您随后获取索引0,因此它应该抛出一个索引器
演示代码:
from Tkinter import *
master = Tk()
listbox = Listbox(master)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
def callback():
items = map(int, listbox.curselection())
if(len(items) == 0):
print "No items"
else:
print items
button = Button(master,text="press",command=callback)
button.pack()
mainloop()
根据上面代码的行为(nothing selected返回空列表),当您没有选择任何内容时,代码应该抛出索引器。。。现在您只需要处理异常:
try:
self.index = int(self._Listbox.curselection()[0])
except IndexError:
tkMessageBox.showwarning("Oops","Need to select something")
最后,我想我会在标准Tkinter对话框(tkMessageBox
module)上留下一个
try:
self.index = int(self._Listbox.curselection()[0])
except IndexError:
tkMessageBox.showwarning("Oops","Need to select something")