0

I am just learning how to write simple GUI app in tkinter and I am stuck on a point when I want to close child1 as the first step of child2 function.

What I want to achieve is on the click of "next button" previous window is closed and new is appear. Here an example of my python3 code. Browsed information on TopLevel on the internet, but without any luck.

Sorry for stupid question, but got no one else to ask :(

from tkinter import *

class TestApp:
    def __init__(self, master):
        self.master = master
        master.minsize(width=800, height=640)

        self.button = Button(master, text='Next', command=self.firstWindow)
        self.button.pack()

    def firstWindow(self):
        self.master.withdraw()
        newWindow = Toplevel(self.master)
        newWindow.minsize(width=800, height=640)

        self.button = Button(newWindow, text='Next', command=self.secondWindow)
        self.button.pack()

    def secondWindow(self):
        CODE TO CLOSE FIRST CHILD HERE
        second_newWindow = Toplevel(REFERENCE TO FIRST CHILD HERE?)
        second_newWindow.minsize(width=800, height=640)

        self.button = Button(second_newWindow, text='Quit', command=self.master.quit())
        self.button.pack()

3 Answers3

0

You can use self.newWindow.destroy() to close your first window.

hypadr1v3
  • 543
  • 4
  • 26
0

Referencing Nazar Khan's answer, you need to declare it as an object of self: self.newWindow = Toplevel(self.master) Then you can close it using self.newWindow.destroy().

tigerninjaman
  • 393
  • 3
  • 17
  • I've tried both before posting here. Always returns an error " self.newWindow.destroy() AttributeError: 'TestApp' object has no attribute 'newWindow'" – Vladislav Kulbatski Aug 15 '18 at 08:42
0

Thanks to the author I've found an error:

naming for newWindow should be named as

self.

in its function.

from tkinter import *

class TestApp:
    def __init__(self, master):
        self.master = master
        master.minsize(width=800, height=640)

        self.button = Button(master, text='Next', command=self.firstWindow)
        self.button.pack()

    def firstWindow(self):
        self.master.withdraw()
        self.newfirstWindow = Toplevel(self.master)
        self.newfirstWindow.minsize(width=800, height=640)

        self.button = Button(self.newfirstWindow, text='Next', command=self.secondWindow)
        self.button.pack()

    def secondWindow(self):
        self.newfirstWindow.destroy()
        self.newsecondWindow = Toplevel(self.master)
        self.newsecondWindow.minsize(width=800, height=640)

        self.button = Button(self.newsecondWindow, text='Quit', command=self.master.quit())
        self.button.pack()





if __name__ == "__main__":
    master = Tk()
    App = TestApp(master)
    master.mainloop()