[Python] Why does my approach to destroy window fail?

Discussão em 'Python' iniciado por Stack, Maio 18, 2025.

  1. Stack

    Stack Membro Participativo

    I want the EXIT button to close the window but I get the following error:

    self.button=ttk.Button(self, text=' EXIT', command=app.exit).grid(column=0, row=0, sticky='ew') NameError: name 'app' is not defined. Did you mean: 'App'?

    Can someone tell me why and how to fix it please?

    #!/usr/bin/python3.9

    import tkinter as tk
    from tkinter import ttk

    class ButtonFrame(ttk.Frame):
    def __init__(self, container):
    super().__init__(container)

    self.__create_widgets()

    def __create_widgets(self):

    self.button=ttk.Button(self, text=' EXIT', command=app.exit).grid(column=0, row=0, sticky='ew')
    self.grid(padx=0, pady=0)

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

    self.configure(bg='#ff3800')
    self.geometry("500x200") # wxh
    self.resizable(False, False)

    # layout on the root window
    self.columnconfigure(0, weight=1)

    self.__create_widgets()

    def __create_widgets(self):

    # create the button frame
    button_frame = ButtonFrame(self)
    button_frame.grid(column=0, row=0)

    def exit(self):
    self.destroy()


    if __name__ == "__main__":

    app = App()

    app.mainloop()

    Continue reading...

Compartilhe esta Página