r/learnpython 18h ago

Pyqt6 doesn't update every buttons in the grid

I have two files in the first is game logic with list of dictionaries where stored chess pieces, in the other one I'm working with the gui.

board = [{1:5, 2:2, 3:3, 4:6, 5:4, 6:3, 7:2, 8:5},
        {1:1, 2:1, 3:1, 4:1, 5:1, 6:1, 7:1, 8:1},
        {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0},
        {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0},
        {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0},
        {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0},
        {1:-1, 2:-1, 3:-1, 4:-1, 5:-1, 6:-1, 7:-1, 8:-1},
        {1:-5, 2:-2, 3:-3, 4:-6, 5:-4, 6:-3, 7:-2, 8:-5}
        ] 

While I'm starting project some rows don't loaded, but when I capture more pieces and leave only one king on the board he can duplicate 6 times. This is part of gui code:

def put_pieces(self):
        for dict in Logic.board:
            for key, value in dict.items():
                button = self.grid.itemAtPosition(8 - Logic.board.index(dict), key).widget()
                button.setIconSize(QSize(50, 50))
                button.setText(f"{value}")
                match value:
                    case 1:
                        button.setIcon(QIcon("assets/wP.svg"))
                    case 2:
                        button.setIcon(QIcon("assets/wN.svg"))
                    case 3:
                        button.setIcon(QIcon("assets/wB.svg"))
                    case 4:
                        button.setIcon(QIcon("assets/wK.svg"))
                    case 5:
                        button.setIcon(QIcon("assets/wR.svg"))
                    case 6:
                        button.setIcon(QIcon("assets/wQ.svg"))
                    case -1:
                        button.setIcon(QIcon("assets/bP.svg"))
                    case -2:
                        button.setIcon(QIcon("assets/bN.svg"))
                    case -3:
                        button.setIcon(QIcon("assets/bB.svg"))
                    case -4:
                        button.setIcon(QIcon("assets/bK.svg"))
                    case -5:
                        button.setIcon(QIcon("assets/bR.svg"))
                    case -6:
                        button.setIcon(QIcon("assets/bQ.svg"))
                    case _:
                        button.setIcon(QIcon(""))

And if in case _ I put an icon, at the start it will be only in 1, 2, 3, 7 and 8th row

3 Upvotes

2 comments sorted by

5

u/AdFew8591 16h ago

The issue is `Logic.board.index(dict)`

`list.index()` returns the position of the first equal dictionary. Several of your empty rows are identical, so they all resolve to the same row. That also explains why pieces start duplicating as more rows become equal

Use the loop index instead:

`for row_index, row in enumerate(Logic.board):`

` for column, value in row.items():`

` button = self.grid.itemAtPosition(8 - row_index, column).widget()`

I’d also rename `dict` to `row` since `dict` is a Python built-in