首页 > 解决方案 > 连接两个字符串时Python无法找到变量

问题描述

这似乎是一个非常愚蠢的问题,但它让我很生气。我几天前才开始使用 Python,在使用其他语言一段时间后,我遇到了一个非常奇怪的问题。我正在尝试将一个名为“word”的顶级字符串变量设置为自身和一个字母的连接。Python 能够很好地找到变量,如下所示。

声明

但是,每当我尝试连接时,我都会突然收到一条错误消息,告诉我 Python 无法找到该变量。

的声明

黄色波浪线是我的 IDE,告诉我找不到该变量。我已经尝试直接从其他堆栈交换帖子中直接复制+粘贴其他解决方案。在连接方面遇到这么多麻烦有点尴尬,但我已经尝试了大部分我能想到的东西。

编辑:这是我的代码。如您所见,“word”在文件顶部初始化:


word_dict = PyDictionary()
repeats = 5
word = "e"



 def handle_input(x, y, letter): 
    word += letter

    print(word)

    coords = make_coords(x, y)
    for list in grid:
        for button in list:
           button.update(disabled=True)
    for coord in coords:
        x = coord[0]
        y = coord[1]
        list = grid[y]
        button = list[x]
        button.update(disabled=False)



标签: python

解决方案


由于您word是在函数之外定义的,因此您需要将其重新声明为全局变量:

def handle_input(x, y, letter): 
  global word #add this line
  word += letter

  print(word)

  coords = make_coords(x, y)
  for list in grid:
      for button in list:
          button.update(disabled=True)
  for coord in coords:
      x = coord[0]
      y = coord[1]
      list = grid[y]
      button = list[x]
      button.update(disabled=False)

推荐阅读