Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Tkinter中使用curselection选择“不说话”_Python_Tkinter - Fatal编程技术网

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")