[Tutor] OOP help needed

Jim Byrnes jf_byrnes at comcast.net
Tue Jul 26 23:44:42 EDT 2016


OOP has always driven me crazy.  I read the material and follow the 
examples until I feel I understand them, but when I try to implement it 
I end up with an error filled mess.

So I decided to give it another try.  When I got to the chapter on 
tkinter I decided to solve all the exercises using OOP even though the 
book solutions did not use OOP. The first one went fine:

#exer1.py

import tkinter

class Goodbye:
   def __init__(self):

     self.frame = tkinter.Frame(window)
     self.frame.pack()

     self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
       #command=quit)
       command=lambda: quit() )
     self.goodbye_button.pack()

   def quit():
     self.window.destroy()

if __name__=='__main__':
   window = tkinter.Tk()
   myapp = Goodbye()
   window.mainloop()

The second one was more trouble but I finally got it to work.

# exer2.py

import tkinter

class Count:

   def __init__(self):
     ''' Increment a button labeled 0, by 1 with each click '''
     self.frame = tkinter.Frame(window)
     self.frame.pack()
     self.label = tkinter.StringVar()
     self.label.set('0')
     self.count_btn = tkinter.Button(self.frame, textvariable=self.label,
       command=lambda: self.increment(self.label ))
     self.count_btn.pack()

   def increment(self, label):
     count = int(self.label.get())
     self.label.set(str(count + 1))

if __name__ == '__main__':
   window = tkinter.Tk()
   myapp = Count()
   window.mainloop()

I am having trouble understanding the difference between the two lines 
that contain lambda: command= .In exer1.py I can do command=lambda: 
quit().  In exer2.py if I do command=lambda: increment(self.label) I get 
this error:

Exception in Tkinter callback
Traceback (most recent call last):
   File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
     return self.func(*args)
   File "exer2.py", line 14, in <lambda>
     command=lambda: increment(self.label ))
NameError: name 'increment' is not defined

Why do I get this error?  The situations look the same to me but they 
must be different somehow and I just don't see the difference.

Thanks,  Jim



More information about the Tutor mailing list