-5

When I compile this code:

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

I get an ERROR:

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

What is going on?

somerandomdev49
  • 177
  • 1
  • 3
  • 11
  • 1
    Please create a [mcve]. Most likely, you have code that is calling `compileF` before you actually define the global `text` variable. – Bryan Oakley Jan 26 '18 at 19:56
  • Possible duplicate of [How to change a variable after it is already defined in Python](https://stackoverflow.com/questions/41369408/how-to-change-a-variable-after-it-is-already-defined-in-python) – Nae Jan 26 '18 at 20:48

1 Answers1

-1

Sure, the variable is declared AFTER it's used, exactly what Python complains about. Move the top-level text assignment to before the function definition.

bipll
  • 11,747
  • 1
  • 18
  • 32
  • That's not quite it. It might be, but I don't think for the reasons you think. The above is perfectly valid code. It's not the order that the function and variable are defined, it's the order in which the variable is defined and the function is _executed_. – Bryan Oakley Jan 26 '18 at 19:56
  • Hey! I tried to do this! In my first code it was at the top, but it didn't work! – somerandomdev49 Jan 29 '18 at 17:39