string indices must be integers error from a for loop but I'm passing an integer

358 views Asked by At

I'm having trouble understanding this error from my code "TypeError: string indices must be integers" due to the fact I believe that I'm already passing the integer to the code:

    def col1_button_click(self, x, y):
            p = self.players_lst[self.currnt_player_index]

            for x in range(6,0,-1):
                    if self.buttons_2d_list[x][0]["text"] == self.__space:
                            button = self.buttons_2d_list[x][0]
                            button["text"] = p.get_player_symbol()
                            self.gboard.make_move(x, 0, p.get_player_symbol())

                            winner = self.gboard.check_winner() # The board will check after each move, if any player has won the game

                            is_full = self.gboard.is_board_full()

                            if winner == True:
                                                    # Show current player's symbol as Winner, 
                                                            # and terminate the game
                                    win_messge = ("Player %s is the Winner!" % p.get_player_symbol())
                                    messagebox.showinfo("Winner Info ",win_messge)
                                    self.mw.destroy()
                                    exit()

                            if is_full == True:
                                    messagebox.showinfo("Winner Info", "The game ended in a draw!")
                                    self.mw.destroy()
                                    exit()
                            else:
                                    pass

                            if self.currnt_player_index == 1:
                                    self.currnt_player_index = 0
                            else:
                                    self.currnt_player_index+=1 # increment index by 1

                            p = self.players_lst[self.currnt_player_index]
                            p.play()

The error is from this line, 4th one down:

  if self.buttons_2d_list[x][0]["text"] == self.__space:

but from my understanding, I'm already passing integers from the range above the line instead of X, if anyone could describe where I've gone wrong, I would be very grateful :)

2

There are 2 answers

2
Yoav Glazner On

self.buttons_2d_list[x][0] must be a string... print it before and see whats inside

...
print(self.buttons_2d_list[x][0])
if self.buttons_2d_list[x][0]["text"] == self.__space:
    ...

if it returns a string then you are doing:

"string"['text']  

which is wrong ...

0
Marvo On

If

self.buttons_2d_list[x][0]

is a dictionary, you can access the value of the key "text" by writing

self.buttons_2d_list[x][0]["text"]

but if it is anything else you have to access its elements by an integer index like

self.buttons_2d_list[x][0][42]