[Tutor] Turning some Tkinter stuff into classes

Michael P. Reilly arcege@shore.net
Sat, 17 Feb 2001 08:05:06 -0500 (EST)


> 
> I have the following code which *seems* to work ok:
> 
> --------------------------------
> from Tkinter import *
> 
> class Popup:
>         def __init__(self,master):
>                 self.win = Toplevel(master)
> 
> def popup():
>         newwin = Popup(root)
> 
> class PopupButton:
>         def __init(self,master):
>                 self.button = Button(master,text="New!",command=popup)
>                 self.button.pack()
> 
> root = Tk()
> button = PopupButton(root)
> 
> root.mainloop()
> --------------------------------
> 
> The problem is that the definition of "popup" is stylistically horrible
> (I think - I'm still rather new to Object Oriented Programming) since it
> has to refer to the fixed object root, but I'm using it within the class
> PopupButton, so could theoretically create another object with no
> reference to root using this class.  My attempt to create a better
> definition inside the class definition was as follows:
> 
> ---------------------------
> from Tkinter import *
> 
> class Popup:
>         def __init__(self,master):
>                 self.win = Toplevel(master)
> 
> class PopupButton:
>         def __init__(self,master):
>                 self.button=Button(master,text="New!",command=self.popup(master))
>                 self.button.pack()
> 
>         def popup(self,master):
>                 self.newwin = Popup(master)
> 
> root = Tk()
> button = PopupButton(root)
> 
> root.mainloop()
> ----------------------------------------
> 
> Of course, the above didn't work - I got the new popup window
> immediately and the button didn't do anything.  Other attempts to do a
> similar thing (deleting the master reference in the various bits of the
> popup command) produced syntax errors.
> 
> Any suggestions to correct what it is wrong in my second attempt?

Hi there,

You are calling a function when the Button is created, not passing
which function to call at a later point.

class PopupButton:
        def __init__(self,master):
                # store the master widget for the popup
                self.master = master
                # pass the method
                self.button=Button(master,text="New!",command=self.popup)
                self.button.pack()

        # pass only the class instance, self
        def popup(self):
                # get master from the member stored in __init__
                self.newwin = Popup(self.master)

Good luck,
  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------