1

How can I hide the MAIN window when the SECOND window is opened and then make the MAIN window reappear when the SECOND window is closed?

I understand the use of withdraw() and deiconify() but not sure how to apply them in this situation.

The reason for this would be to eventually create a program which the MAIN window acts as a menu which hides when other windows are opened from it and reappears when these other windows are exit.

from tkinter import *

class Main():

    def __init__(self, master):
        self.master = master
        self.title = "Main Window"

        self.button1 = Button(self.master, text="Click Me", command = self.Open)
        self.button1.grid(row=0, column=0, sticky=W)
        self.button2 = Button(self.master, text="Close", command = self.Close)
        self.button2.grid(row=1, column=0, sticky=W)


    def Open(self):
        second_window = Toplevel(self.master)
        window2 = Second(second_window)

    def Close(self):
        self.master.destroy()


class Second():

    def __init__(self, master):
        self.master = master
        self.title = "Second Window"



root = Tk()
main_window = Main(root)
root.mainloop()

Any help would be greatly appreciated.

1 Answer 1

4

You can put a binding on <Destroy> of the second window which will call a function that will call deiconify on the master.

This would be easier in your code if Second was a subclass of Toplevel. If you did that, you could hide this code inside the definition of Second. For example:

...
def Open(self):
    second_window = Second(self.master)
...

class Second(Toplevel):

    def __init__(self, master):
        Toplevel.__init__(self, master)
        self.master = master
        self.master.withdraw()
        self.bind("<Destroy>", self.on_destroy)

    def on_destroy(self, event):
        if event.widget == self:
            self.master.deiconify()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.