[Tutor] Global name not found, though clearly in use

Steven D'Aprano steve at pearwood.info
Wed Jul 14 17:17:53 CEST 2010


On Thu, 15 Jul 2010 12:18:58 am Corey Richardson wrote:
> Hey tutors. Two separate submissions one day, guess I'm getting busy
> ;)
>
> Anyway, I'm re-writing my hangman program to make use of my new-found
> understanding of OOP, and using a GUI this time around. I decided on
> coding with Tkinter, to get my feet wet with GUI stuff.

With respect, I'm not sure your new-found understanding is that 
complete, if you're having problems with simple variables. Have you 
considered doing some basic tutorials to ensure your understanding of 
Python has a solid foundation?

> Here is the traceback:
>
> Traceback (most recent call last):
>   File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__
>     return self.func(*args)
>   File "C:/Users/Corey/Desktop/HangmanApp.py", line 45, in getLetter
>     self.guess = eWordEntryBox.get()
> NameError: global name 'eWordEntryBox' is not defined
>
> However, not even 30 lines down, (29, to be exact) there is this
> line: eWordEntryBox = tk.Entry(fWordEntry)

Without seeing your actual code, it's impossible to say what's going on 
except in vague generalities. But consider a program made of just TWO 
lines:

print(x)
x = 1

What do you expect will happen? If you are surprised that Python will 
raise NameError when it tries to print the value of x, then you really 
should do some basic tutorials.

At the point that the line "print x" is called, x hasn't been defined 
*yet*, and so it doesn't exist. My guess is that your error is exactly 
the same -- you might have a line that defines eWordEntryBox 29 lines 
further down, but at the point that the error occurs, that line hasn't 
been reached yet, and so eWordEntryBox doesn't exist:

self.guess = eWordEntryBox.get()  # Error occurs here
...
...
29 lines of code
...
...
eWordEntryBox = tk.Entry(fWordEntry)  # Defined for the first time!


> Not understanding what is happening here. Same happens when I tack
> self at the beginning of it, except it says global name self is not
> defined.

You can't just "tack" self at the beginning of variables and expect it 
to work, any more than you could tack on "akjfhbcvgsaj" and hope for 
the best! You need to understand *where* the variable self exists, and 
*what* value it has.




-- 
Steven D'Aprano


More information about the Tutor mailing list