2017-01-01 54 views
1

我无法从我的代码“TypeError:字符串索引必须是整数”理解此错误,因为我相信我是已经传递整数代码:字符串索引必须是for循环的整数错误,但我传递一个整数

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

的误差是这条线,4号一跌:

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

但是从我的理解,我已经从范围传递线以上的整数而不是X,如果有人能描述我出错的地方,我会非常感谢:)

+0

文本很好,它得到了一个tkinter按钮的文本。如果我将x更改为任意数字,它会起作用,所以我不知道为什么范围没有传递给x。 –

回答

0

self.buttons_2d_list [X] [0]必须是一个字符串... 打印之前,看看里面什么

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

如果它返回一个字符串,那么你正在做的:

"string"['text'] 

这是不对的......

+0

什么都不打印,只是返回上述错误。我还应该提到我正在使用tkinter,并且这个操作发生在按钮按下时。 –

+0

也许它的空字符串“”...尝试打印(类型(self.buttons_2d_list [x] [0])) –

0

如果

self.buttons_2d_list[x][0] 

是一个字典,你可以通过编写

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

访问键“文本”的价值,但如果是其他任何你有一个整数索引来访问它的元素,如

self.buttons_2d_list[x][0][42] 
相关问题