confusion between global names and instantiated object variable names

W

wanwan

I'm trying to make a GUI, but for some of the instantiated object
variable names, the interpreter is looking at them as global names.
Here is an example of what I did:


class mygui:


def __init__(self, root):

self.menubar = Menu(root)

# Game Menu
self.menu1 = Menu(self.menubar, tearoff=0)
self.menu1.add_command(label="Open File", command=donothing)
self.menu1.add_separator()
self.menu1.add_command(label="Exit", command=root.quit)
self.menubar.add_cascade(label="File", menu=self.menu1)

# ignoring the rest of the program ...


when I run my example, an error shows:
"NameError: global name'menubar' is not defined"

I wonder why it doesn't work. Isn't that the way to define an object
variable?

Any response would be appreciated.
 
P

Piet van Oostrum

wanwan said:
w> I'm trying to make a GUI, but for some of the instantiated object
w> variable names, the interpreter is looking at them as global names.
w> Here is an example of what I did:

w> class mygui:

w> def __init__(self, root):
w> self.menubar = Menu(root)
w> # Game Menu
w> self.menu1 = Menu(self.menubar, tearoff=0)
w> self.menu1.add_command(label="Open File", command=donothing)
w> self.menu1.add_separator()
w> self.menu1.add_command(label="Exit", command=root.quit)
w> self.menubar.add_cascade(label="File", menu=self.menu1)
w> # ignoring the rest of the program ...

w> when I run my example, an error shows:
w> "NameError: global name'menubar' is not defined"

If it talks about global name, it can't be self.menubar or
anything.menubar. So there must be a soloist menubar reference somewhere.
Doesn't it tell you the line number?
 
A

Alex Martelli

wanwan said:
when I run my example, an error shows:
"NameError: global name'menubar' is not defined"

I wonder why it doesn't work. Isn't that the way to define an object
variable?

The code you posted should not trigger this error. Most likely problem:
you have typed a comma where you meant to type a dot, for example
instead of self.menubar you wrote self,menubar somewhere -- it's a hard
error to spot with certain fonts.


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,268
Messages
2,571,344
Members
48,019
Latest member
Migration_Expert

Latest Threads

Top