Search code examples
pythonwxpython

wxPython adding list to grid with while loop


I'm trying to input a list to a grid and whenever I run it I get this error: SetValue(): invalid row or column index in wxGridStringTable. I apologise if it's something simple as I've only started learning python recently.

Code:

import wx
import wx.grid

class main(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        items = ["milk", "cherries", "soup"]
        total = len(items)
        grid = wx.grid.Grid(self)
        grid.SetRowLabelSize(0)
        grid.SetColLabelSize(0)
        grid.CreateGrid(total, 1)
        listItem = 0
        while listItem < total:
            grid.SetCellValue(listItem + 1, 1, items[listItem])
            listItem += 1

if __name__ == "__main__":
    app = wx.App(False)
    frame = main()
    frame.Show()
    app.MainLoop()

Solution

  • The code is trying to set the values starting at row 1, col 1 but the rows and cols are zero based. Also instead of using a while loop, its better to use a for loop with enumerate to get the index of the item.

    import wx
    import wx.grid
    
    class main(wx.Frame):
        def __init__(self):
            wx.Frame.__init__(self, None)
            items = ["milk", "cherries", "soup"]
            total = len(items)
            grid = wx.grid.Grid(self)
            grid.SetRowLabelSize(0)
            grid.SetColLabelSize(0)
            grid.CreateGrid(total, 1)
            for index, value in enumerate(items):
                grid.SetCellValue(index, 0, value)
    
    
    if __name__ == "__main__":
        app = wx.App(False)
        frame = main()
        frame.Show()
        app.MainLoop()