Tkinter (OOP?) help

Mike Meyer mwm at mired.org
Thu Dec 30 21:38:04 EST 2004


"3c273" <nospam at nospam.com> writes:

> Hello,
> I am trying to expand on a tutorial I am working through and I am not
> understanding something. In the following example if you click on the "New
> window" button, a new window appears with a "Close me" button in it and if
> you click on it's "Close me" button, it works. But, if you click the
> original "New window" button two or more times, the "Close me" button only
> works on one of the new windows. Furthermore, if you click "Close me" on the
> first new window, it closes the last window to open, not the one that you
> clicked on. How do I bind a "closeme2" function to each new window? Any help
> is appreciated.
>
> Louis
>
> --begin code--
> from Tkinter import *
>
> class MyApp:
>     def __init__(self, parent):
>         self.myparent = parent
>         self.frame1 = Frame(parent)
>         self.frame1.pack()
>
>         self.btn1 = Button(self.frame1, text='Do nothing', bg='green')
>         self.btn1.pack(side=LEFT)
>
>         self.btn2 = Button(self.frame1, text='Close me', fg='white',
> bg='red')
>         self.btn2.pack(side=LEFT)
>         self.btn2.bind('<Button-1>', self.closeme)
>
>         self.btn3 = Button(self.frame1, text='New window?', bg='grey')
>         self.btn3.pack(side=LEFT)
>         self.btn3.bind('<Button-1>', self.newwindow)
>
>     def closeme(self, event):
>         self.myparent.destroy()
>
>     def newwindow(self, event):
>         self.new = Toplevel(self.myparent)
>         self.frame2 = Frame(self.new)
>         self.frame2.pack()
>
>         self.btn4 = Button(self.frame2, text='Close me', fg='white',
> bg='red')
>         self.btn4.pack()
>         self.btn4.bind('<Button-1>', self.closeme2)
>
>     def closeme2(self, event):
>         self.new.destroy()

Every time you call newwindow, you rebind self.new to the window just
created. So any close button that works will close the last window opened.

You need to create a separate class for new windows, each with it's
own self.new (or self.window) that it's self.closeme will call destroy
on.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list