Python tkinter cloase first window while opening second window

  Kiến thức lập trình

I’m trying to close the first window as the second window opens. The first window fails to close, and there is no error message.

This question has a similar problem but was solved by addressing the imported libraries: Tkinter is opening a second windows when the first one is closing

Here’s my code, which was taken from here https://www.pythontutorial.net/tkinter/tkinter-toplevel/

import tkinter as tk
from tkinter import ttk


class Window(tk.Toplevel):
    def __init__(self, parent):
        super().__init__(parent)

        self.geometry('300x100')
        self.title('Toplevel Window')

        ttk.Button(self,
                text='Close',
                command=self.destroy).pack(expand=True)


class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.geometry('300x200')
        self.title('Main Window')

        # place a button on the root window
        ttk.Button(self,
                text='Open a window',
                command=self.open_window).pack(expand=True)

    def open_window(self):
        window = Window(self)
        window.grab_set()
        self.destroy


if __name__ == "__main__":
    app = App()
    app.mainloop()

I added in self.destroy in the function def open_window(self). But it doesn’t close the window created by this class: class App(tk.Tk).

LEAVE A COMMENT