错误:UnboundLocalError:赋值前引用的局部变量

时间:2018-01-26 12:56:18

标签: python tkinter

编译此代码时:

def compileF():
    file = text.get('1.0', END)
    print(file)
text = Text(root, height=40, width=60, fg="black", font="Helvetica 12")

我收到错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:\Users\MIK\Desktop\GranitePad\GranitePad.pyw", line 16, in compileF
    file = text.get('1.0', END)
UnboundLocalError: local variable 'text' referenced before assignment

发生了什么事?

1 个答案:

答案 0 :(得分:-1)

当然,变量是在它被使用之后声明的,正是Python抱怨的。将顶级text赋值移到函数定义之前。