• Import the tkinter library and create an instance of tkinter frame.

  • Set the size of the frame ">

    How to exit from Python using a Tkinter Button?



    To exit from Python using a Tkinter button, you can follow the steps given below −

    Steps −

    • Import the tkinter library and create an instance of tkinter frame.

    • Set the size of the frame using geometry method.

    • Define a function close() to close the window. Call the method win.destroy() inside close().

    • Next, create a button and call the close() function.

    • Finally, run the mainloop of the application window.

    Example

    # Import the library
    from tkinter import *
    
    # Create an instance of window
    win = Tk()
    
    # Set the geometry of the window
    win.geometry("700x350")
    
    # Title of the window
    win.title("Click the Button to Close the Window")
    
    # Define a function to close the window
    def close():
       #win.destroy()
       win.quit()
    
    # Create a Button to call close()
    Button(win, text= "Close the Window", font=("Calibri",14,"bold"), command=close).pack(pady=20)
    
    win.mainloop()

    Output

    On execution, it will produce the following output −

    On clicking the button, it will close the window.

    Instead of win.destroy(), you can also use win.quit() to close the application. However, there is a subtle difference between the two. win.quit() abruptly quits the application which means the mainloop will still be running in the background. win.destroy() on the other hand terminates the mainloop and destroys all the widgets inside the window.

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements