首页 > 解决方案 > Getting a 'bad listbox index' error when trying to return a value from cursor selection in tkinter listbox

问题描述

Trying to return the value from the cursor selection for a listbox with tkinter, but I'm getting an error:

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

I can't figure out why since I was using listbox.get(listbox.curselection()) just fine earlier in a similar situation.

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

I need the entry boxes to produce the dictionary values in the .dat file, the key being the country name which is what I'm trying to get the value of from the cursor selection in the listbox.

标签: pythontkinter

解决方案


You are calling listbox.curselection() just a few milliseconds after creating the listbox. Nothing is selected because the user hasn't had a chance and you're not programmatically selecting anything, so your code throws an error.


推荐阅读