Tkinter (OOP?) help

3c273 nospam at nospam.com
Thu Dec 30 18:09:34 EST 2004


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()

root = Tk()
root.title('Tk Test Program')
myapp = MyApp(root)
root.mainloop()





More information about the Python-list mailing list