【问题标题】:Python 3.2.1: Variable Referenced Before Assignment, Previously WorkingPython 3.2.1:赋值前引用的变量,以前工作
【发布时间】:2011-11-19 00:42:53
【问题描述】:

我在这里搜索过类似的问题,但找不到确切的答案。我不断收到“...在分配前引用”错误。

我试图将从一个函数返回的两个图形对象放入另一个函数的两个变量中。

我在早期版本中有基本完全相同的代码,它工作得很好。

我有一段代码:

if moveE:
    moved_ctr, nT = MoveCharacter(ctr, spaceSize, borderSet, "east")
if moveW:
    moved_ctr, nT = MoveCharacter(ctr, spaceSize, borderSet, "west")
moved_ctr.draw(board)

这就是 MoveCharacter() 的样子:

def MoveCharacter(character, spSz, bdSet, direction):
    x1 = character.getCenter().getX()
    x2 = bdSet
    y1 = character.getCenter().getY()
    y2 = bdSet
    notifyText = Text(Point(100, 100), "")

    character.undraw()

    distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

    if direction == "east":
            if distance < spSz:
                    character.move(spSz, 0)
            else:
                    notifyText.setText("You cannot move right from where you currently are.")
    if direction == "west":
            if distance > spSz:
                    character.move(-1 * spSz, 0)
            else:
                    notifyText.setText("You cannot move left from where you currently are.")

    return character, notifyText

我不断收到错误:

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    Grid()
  File "<pyshell#24>", line 70, in Grid
    moved_ctr.draw(board)
UnboundLocalError: local variable 'moved_ctr' referenced before assignment

【问题讨论】:

  • in an earlier version 是什么? (面对模棱两可,拒绝猜测的诱惑)。

标签: python graphics return


【解决方案1】:

if moveE: 之前会发生什么?

moveEmoveW 很可能是假的。

【讨论】:

  • 这个:moveE = rectIntersect(gE, click) moveW = rectIntersect(gW, click)if moveE: 之前的内容。同样,该代码与以前保持不变,当我单击相应的按钮时它返回TruerectIntersect() 只是一个教师提供的函数,用于检查鼠标点击是否在给定的矩形内。虽然现在我测试了当我单击这些相应的按钮时这些值是什么,但这可能是问题所在。
  • 出于调试目的,可能值得同时打印moveEmoveW。您的问题似乎是两者都是False,所以maved_ctr 没有被分配到。
  • @Dougal:当我打印moveEmoveW 时,他们会说False,无论我是否点击其中任何一个。不过,我正试图弄清楚为什么它现在不起作用,因为早些时候,我得到了一个返回 True 和另一个 False,这意味着它一切都正确,它会根据哪个是正确的采取适当的行动点击。
  • 当你“点击”什么?询问有关您正在使用的特定图形 API 以及您从 UI 获得的值的新问题。
猜你喜欢
  • 2014-01-10
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-14
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多