[Tutor] keep from opening multiple Toplevel windows

Alan Gauld alan.gauld at btinternet.com
Sat Oct 4 15:34:46 CEST 2008


<dwbarne at earthlink.net> wrote

> The behavior I seek is that one and only one Toplevel window
> gets generated no matter how many times the original Tkinter
> button is pressed.

Here is a minimal example of what I think you want?

Does that help?

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

--------------------------------------------------
# TestTopLevel.py

from Tkinter import *


class MainWin(Frame):
    def __init__(self, parent, sub=None):
        Frame.__init__(self, parent)
        self.parent = parent
        Label(self, text="This is the main window").pack()
        self.bShow = Button(self, text="Show Sub", command = 
self.doShow)
        self.bShow.pack()
        self.bQuit = Button(self, text="Quit", command = self.quit)
        self.bQuit.pack()
        self.sub = sub
        self.pack()

    def doShow(self):
       try: self.sub.deiconify()
       except:
           self.sub = SubWindow(self.parent)
           self.sub.withdraw()
           self.sub.deiconify()

class SubWindow(Toplevel):
    def __init__(self, parent):
        Toplevel.__init__(self, parent)
        Label(self, text="Child Window").pack()
        self.bClose = Button(self, text="Close", command=self.doClose)
        self.bClose.pack()
        self.withdraw()

    def doClose(self):
        self.withdraw()


def main():
   app = Tk()
   m = MainWin(app, SubWindow(app))
   app.mainloop()

if __name__ == "__main__": main()





More information about the Tutor mailing list