Search code examples
stringlistboxwxpython

How to get string from listbox


I have very complicated problem. I´ve search whole internet and tried everything, but nothing worked. I want get string from listbox and than delete line in file with word from listbox. Can please somebody help me? Here is code:

def OnDelete(self, event):
sel = self.listbox.GetSelection()
if sel != -1:
self.listbox.Delete(sel)
subor = open("Save/savegame.txt", "r")
lines = subor.readlines()
subor.close()
subor = open("Save/savegame.txt", "w")
selstring = self.listbox.GetString(self.listbox.GetSelection())
for line in lines:
if line!=selstring:
subor.write(line)
subor.close()

And this is code for saving file:
def OnNewGame(self,event):
nameofplr = wx.GetTextFromUser('Enter your name:', 'NEW GAME')
subor=open("Save/savegame.txt","a")
subor.write( "\n" + nameofplr)
subor.close()
savegame=open("Save/" + nameofplr + ".prjct", "w+")
savegame.close()

It shows this error:

Traceback (most recent call last): File "D:\Python\Python Projects\Project\Project.py", line 106, in OnDelete selstring = self.listbox.GetString(self.listbox.GetSelection()) File "D:\Python\lib\site-packages\wx-3.0-msw\wx_core.py", line 12962, in GetString return core.ItemContainer_GetString(*args, **kwargs) wx._core.PyAssertionError: C++ assertion "IsValid(n)" failed at ....\src\msw\listbox.cpp(387) in wxListBox::GetString(): invalid index in wxListBox::GetString

Thank you very much for help!


Solution

  • Think about how your program works: In the OnDelete method you check which item is selcted, then you delete this item. Then you do something with your file. After that you try to get the string from your selected item, but this was deleted by you.

    You should call Delete after the line

    selstring = self.listbox.GetString(self.listbox.GetSelection())
    

    It would also be nice if you would put your code in a code block, so that we can see the indentation.