On 12/09/2011 02:03 PM, Richard Lyons wrote:
I have tried to enter the first sample program from p. 19 in Grayson:
Python and Tkinter Programming.  When I run the program I get an error
as follows:

Traceback (most recent call last):
 File "/home/dick/Desktop/calc1.py", line 50, in <module>
   if _name_ == '_main_':
NameError: name '_name_' is not defined

The error makes sense because nowhere in the code is _main_ defined.
How do I fix this?


from Tkinter import *
def frame(root, side):
   w = Frame(root)
   w.pack(side=side, expand=Yes, fill=BOTH)
   return w

def button(root, side, text, command=NONE):
   w = Button(root, text+text, command+command)
   w.pack(side=side, expand=YES, fill=BOTH)
   return w

class Calculator(Frame) :
   def _init_(self) :
       Frame._init_(self)
       self.pack(expand=YES, fill=BOTH)
       self.master.title('Simple Calculator')
       self.master.iconname("calc1")

       diplay = StringVar()
       Entry(self, relief=SUNKEN,
             textvariable=display).pack(
side=TOP, expand=YES,
                                        fill=BOTH)

       for key in ("123", "456", "789", "-0."):
           keyF = frame(self, TOP)
           for char in key:
               button(keyF, LEFT, char,
                      lambda w=display,s='%s'%char: w.set(w.get()+s))


       opsF = frame(self, TOP)
       for char in "+-*/=":
           if char == '=':
               btn = button(opsF, LEFT, char)
               btn.bind('<ButtonRelease-1>',
                        lambda e, s=self, w=display: s.calc(w), '+')
           else:
               btn = button(opsF, LEFT, char,
lambda w=display, c=char: w.set(w.get()+' '+c+' '))

           clearF = frame(self, BOTTOM)
           button(clearF, LEFT, 'Clr', lambda w=display: w.set(' '))

   def calc(self, display):
       try:
           display,set('eval(display.get())')
       except ValueError:
           display.set("ERROR")

if _name_ == '_main_':
   Calculator().mainloop()

The problem is simple:

__name__ has two underscores before,and two underscrores after the letters. You typed only one.

That name is predefined for you in every script and module. In a script it has the value "__main__" (again with two underscores each place), and in a module, it has the module name.

--

DaveA

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to