尝试从Tkinter列表框中的游标选择返回值时出现“错误的列表框索引”错误

时间:2019-08-06 00:36:56

标签: python tkinter

试图从带有tkinter的列表框的光标选择中返回值,但是出现错误:

Traceback (most recent call last):
  File "C:/Users/Rachel/PycharmProjects/Final2100/FE1.py", line 36, in <module>
    entvariable1.set(nations[listbox.get(listbox.curselection())]["cont"])
  File "C:\Users\Rachel\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2798, in get
    return self.tk.call(self._w, 'get', first)
_tkinter.TclError: bad listbox index "": must be active, anchor, end, @x,y, or a number

我无法弄清楚为什么,因为在类似情况下,我刚刚使用listbox.get(listbox.curselection())就可以了。

import pickle
from tkinter import *
window = Tk()
def getDictionary(fileName):
    infile = open(fileName, 'rb')
    nations = pickle.load(infile)
    infile.close()
    return nations
nations = getDictionary("UNdict.dat")



lbnations = StringVar()
listbox = Listbox(window, width = 20, listvariable = lbnations)
listbox.grid(padx = 5, pady = 5, row = 0, column = 0, rowspan = 4, sticky = NSEW)
lbnations.set(tuple(nations))

label1 = Label(window, text = "Continent:")
label1.grid(padx = 5, pady = 5, row = 0, column = 2, sticky = E)
label2 = Label(window, text = "Population:")
label2.grid(padx = 5, pady = 5, row = 1, column = 2, sticky = E)
label3 = Label(window, text = "Area (sq. miles):")
label3.grid(padx = 5, pady = 5, row = 2, column = 2, sticky = E)

entvariable1 = StringVar()
entvariable2 = StringVar()
entvariable3 = StringVar()
contentry = Entry(window, state = "readonly", textvariable = entvariable1, width = 13)
contentry.grid(padx = 5, pady = 5, row = 0, column = 1, sticky = W)
popentry = Entry(window, state = "readonly", textvariable = entvariable2, width = 13)
popentry.grid(padx = 5, pady = 5, row = 1, column = 1, sticky = W)
areaentry = Entry(window, state = "readonly", textvariable = entvariable3, width = 13)
areaentry.grid(padx = 5, pady = 5, row = 2, column = 1, sticky = W)

##country = listbox.get(listbox.curselection())
entvariable1.set(nations[listbox.get(listbox.curselection())]["cont"])
entvariable2.set(nations[listbox.get(listbox.curselection())]["popl"])
entvariable3.set(nations[listbox.get(listbox.curselection())]["area"])




window.mainloop()

我需要输入框来生成.dat文件中的字典值,键是国家/地区名称,这就是我想要从列表框中的光标选择中获取值的地方。

1 个答案:

答案 0 :(得分:0)

创建列表框仅几毫秒后,您正在呼叫listbox.curselection()。由于用户没有机会,而且您没有以编程方式选择任何内容,因此未选择任何内容,因此您的代码将引发错误。