With minimal editing to your code (Not sure if they've taught classes or not in your course), change:

def close_window(root): 
    root.destroy()

to

def close_window(): 
    window.destroy()

and it should work.


Explanation:

Your version of close_window is defined to expect a single argument, namely root. Subsequently, any calls to your version of close_window need to have that argument, or Python will give you a run-time error.

When you created a Button, you told the button to run close_window when it is clicked. However, the source code for Button widget is something like:

# class constructor
def __init__(self, some_args, command, more_args):
    #...
    self.command = command
    #...

# this method is called when the user clicks the button
def clicked(self):
    #...
    self.command() # Button calls your function with no arguments.
    #...

As my code states, the Button class will call your function with no arguments. However your function is expecting an argument. Thus you had an error. So, if we take out that argument, so that the function call will execute inside the Button class, we're left with:

def close_window(): 
    root.destroy()

That's not right, though, either, because root is never assigned a value. It would be like typing in print(x) when you haven't defined x, yet.

Looking at your code, I figured you wanted to call destroy on window, so I changed root to window.

Answer from Jesus is Lord on Stack Overflow
Top answer
1 of 6
39

With minimal editing to your code (Not sure if they've taught classes or not in your course), change:

def close_window(root): 
    root.destroy()

to

def close_window(): 
    window.destroy()

and it should work.


Explanation:

Your version of close_window is defined to expect a single argument, namely root. Subsequently, any calls to your version of close_window need to have that argument, or Python will give you a run-time error.

When you created a Button, you told the button to run close_window when it is clicked. However, the source code for Button widget is something like:

# class constructor
def __init__(self, some_args, command, more_args):
    #...
    self.command = command
    #...

# this method is called when the user clicks the button
def clicked(self):
    #...
    self.command() # Button calls your function with no arguments.
    #...

As my code states, the Button class will call your function with no arguments. However your function is expecting an argument. Thus you had an error. So, if we take out that argument, so that the function call will execute inside the Button class, we're left with:

def close_window(): 
    root.destroy()

That's not right, though, either, because root is never assigned a value. It would be like typing in print(x) when you haven't defined x, yet.

Looking at your code, I figured you wanted to call destroy on window, so I changed root to window.

2 of 6
11

You can associate directly the function object window.destroy to the command attribute of your button:

button = Button (frame, text="Good-bye.", command=window.destroy)

This way you will not need the function close_window to close the window for you.

๐ŸŒ
CodersLegacy
coderslegacy.com โ€บ home โ€บ python โ€บ how to close a window in tkinter
How to close a window in Tkinter - CodersLegacy
October 19, 2020 - The destroy function will cause Tkinter to exit the mainloop() and simultaneously, destroy all the widgets within the mainloop(). from tkinter import * def close(): root.destroy() root = Tk() root.geometry('200x100') button = Button(root, text ...
Discussions

Tkinter - how to end main loop using a button
You stop the mainloop with the command root.quit(). Can you describe what your program is meant to do? For simple user input I'd recommend you use the easygui module instead of creating your own. More on reddit.com
๐ŸŒ r/learnpython
8
2
April 21, 2019
python - How do I close a tkinter window? - Stack Overflow
How should I define the quit function to exit my application? ... You should use destroy() to close a Tkinter window. from Tkinter import * #use tkinter instead of Tkinter (small, not capital T) if it doesn't work #as it was changed to tkinter in newer Python versions root = Tk() Button(root, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to exit from Python using a Tkinter Button? - Stack Overflow
As you can see under endProgram() I have tried 2 types of exit commands, both do not work. I never used them together, I was just trying to show what methods I have used so far. These methods were methods I found here and on other websites, but if I try either, I get this error: Traceback (most recent call last): File "C:\Users\Sa'id\Documents\Learning Programming\Python\Tkinter ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Overriding Tkinter "X" button control (the button that close the window) - Stack Overflow
When the user presses a close Button that I created, some tasks are performed before exiting. However, if the user clicks on the [X] button in the top-right of the window to close the window, I can... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-close-a-tkinter-window-with-a-button
How to Close a Tkinter Window With a Button? - GeeksforGeeks
July 23, 2025 - Or, you can use exit() function after mainloop to exit from the Python program. It is not recommended to use quit() if your Tkinter application is executed from IDLE as it will close the interpreter leaving the program running with all its widgets.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-exit-from-python-using-a-tkinter-button
How to exit from Python using a Tkinter Button?
October 26, 2021 - To exit from Python using a Tkinter button, you can use either the destroy() or quit() method.
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ tkinter โ€บ python-tkinter-widgets-exercise-3.php
Python tkinter widgets: Create two buttons exit and hello using tkinter module
August 25, 2025 - text_disp= tk.Button(frame, text="Hello", command=write_text) - Create a "Hello" button (text_disp) that calls the write_text function when clicked. exit_button = tk.Button(frame, text="Exit", fg="green", command=quit) - Create an "Exit" button ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ tkinter - how to end main loop using a button
r/learnpython on Reddit: Tkinter - how to end main loop using a button
April 21, 2019 -

Hi everyone,

I'm not sure how to get this loop to end. This is what I am trying to do:

  1. Main program calls function: input_exercise_number() from my GUI_function program (the code I will show you is the GUI program, not main).

  2. The GUI runs and asks for input from the user. That input is then put into a variable.

  3. THIS PART IS WHERE I AM HAVING TROUBLE: When I press the button, it activates the function user_exercise() to take the user input and put it into a variable. But, I also want to close the main loop so I can open a new Tkinter window for more user input.

How do I also end the loop while calling that function to change the variable?

Code

from tkinter import *

#-------------------------------------------------------------------------------
#---------------------------GUI Prompt for Exercise count-----------------------
#-------------------------------------------------------------------------------
exercise_number = 0

def user_input_exercise_number():

root = Tk()
root.title("Workout Wonder 2000")
root.geometry("448x150+450+250")

#Title
    heading = Label(root, text="Welcome to Workout 2000", font=("arial", 20, "bold"), fg="red").pack()

#label for first input
    workout_exercise_label = Label(root, text="Enter in the amount of exercises" +" you did: ", font=("arial", 10, "bold"), fg="black").place(x=5, y=50)

#create text variable name and create user input for day's workout
    exercise_count = StringVar()

    entry_box = Entry(root, textvariable=exercise_count, width = 25, bg = "lightblue").place(x=280, y=50)

#Create function that receives input from user and stores it as
#a variable. Declares exercise_number as global for 
passing it back
    def user_exercise():
        global exercise_number
        exercise_number = exercise_count.get()
        return exercise_number

#create button that activates a function
    work = Button(root, text="Enter", width=20, height=2, bg="light blue", command=user_exercise,).place(x=280, y=85)

    root.mainloop()

    return exercise_number
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ code.with.dawood
How to close the GUI using Button in Tkinter | Exit button | Python | Code with Dawood - YouTube
In this video, I explained how to make the exit button which close the GUI as well.#python #tkinter #programming #GUI #code
Published ย  February 11, 2022
Views ย  2K
๐ŸŒ
Finxter
blog.finxter.com โ€บ how-to-exit-from-python-using-a-tkinter-button
How to Exit from Python Using a Tkinter Button โ€“ Be on the Right Side of Change
By binding the quit_app function to the โ€œExitโ€ button, we trigger sys.exit() when the button is clicked. This will stop the entire program, which is more abrupt than destroy or quit from Tkinter.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python tkinter โ€บ how to close a tkinter window with a button
How to Close a Tkinter Window With a Button | Delft Stack
February 2, 2024 - We make a separate quit method and then bind it to the command of the button. We could also directly set the command argument to be self.root.destroy as below. try: import Tkinter as tk except: import tkinter as tk class Test: def __init__(self): ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-close-a-tkinter-window-by-pressing-a-button
How to close a Tkinter window by pressing a Button?
#Import the required libraries from tkinter import * #Create an instance of tkinter frame win= Tk() #Set the geometry of frame win.geometry("600x250") #Create a Label Label(win, text="Press the Close Button to close the window", font=('Helvetica bold', 11)).pack(pady=20) #Define a function to close the window def close_win(): win.destroy() #Create a Button for closing the window button= Button(win, text="Close", command=close_win) button.pack(pady=20) win.mainloop()
๐ŸŒ
YouTube
youtube.com โ€บ watch
Python Tkinter Exit Program | How to exit a program in Python Tkinter - YouTube
In this Python Tkinter video tutorial, I will explain how to exit a program in Python Tkinter. Here I will discuss how to use the destroy() method to exit a ...
Published ย  April 18, 2021
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-tkinter-exit-program
Python Tkinter Exit Program - Python Guides
April 18, 2021 - from tkinter import * from tkinter import messagebox from time import * def close(): ws.destroy() ws = Tk() ws.title("PythonGuides") ws.geometry("400x300") ws['bg']='#5d8a82' Button( ws, text="EXIT PROGRAM", font=("Times", 14), command=close ).pack(pady=100) ws.mainloop()
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ tkinter โ€บ python-tkinter-dialogs-and-file-handling-exercise-2.php
Python Tkinter: Implementing a confirmation dialog for exiting
August 25, 2025 - import tkinter as tk from tkinter import messagebox def confirm_exit(): response = messagebox.askyesnocancel("Confirm Exit", "Want to save changes before exiting?") if response is None: # User clicked "Cancel" return elif response: # User clicked "Yes," save_changes() # Close the application root.destroy() def save_changes(): # Implement your save changes logic here messagebox.showinfo("Saved", "Saved successfully!") root = tk.Tk() root.title("Exit Example") exit_button = tk.Button(root, text="Exit", command=confirm_exit) exit_button.pack(padx=20, pady=20) root.mainloop() Explanation: In the exercise above - import tkinter as tk - Import the required library for creating the GUI components.
Top answer
1 of 12
314

Tkinter supports a mechanism called protocol handlers. Here, the term protocol refers to the interaction between the application and the window manager. The most commonly used protocol is called WM_DELETE_WINDOW, and is used to define what happens when the user explicitly closes a window using the window manager.

You can use the protocol method to install a handler for this protocol (the widget must be a Tk or Toplevel widget):

Here you have a concrete example:

import tkinter as tk
from tkinter import messagebox

root = tk.Tk()

def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
2 of 12
49

Matt has shown one classic modification of the close button.
The other is to have the close button minimize the window.
You can reproduced this behavior by having the iconify method
be the protocol method's second argument.

Here's a working example, tested on Windows 7 & 10:

# Python 3
import tkinter
import tkinter.scrolledtext as scrolledtext

root = tkinter.Tk()
# make the top right close button minimize (iconify) the main window
root.protocol("WM_DELETE_WINDOW", root.iconify)
# make Esc exit the program
root.bind('<Escape>', lambda e: root.destroy())

# create a menu bar with an Exit command
menubar = tkinter.Menu(root)
filemenu = tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.destroy)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)

# create a Text widget with a Scrollbar attached
txt = scrolledtext.ScrolledText(root, undo=True)
txt['font'] = ('consolas', '12')
txt.pack(expand=True, fill='both')

root.mainloop()

In this example we give the user two new exit options:
the classic File โ†’ Exit, and also the Esc button.

๐ŸŒ
Python
mail.python.org โ€บ pipermail โ€บ tutor โ€บ 2011-January โ€บ 081205.html
[Tutor] How to insert a quit-Button in a Tkinter class?
September 7, 2013 - Hello, Inherit from Frame see below: from Tkinter import * class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createLabel() self.createButton() def createLabel(self): self.label = Tkinter.Label(text="") self.label.grid() self.update_clock() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.after(1000, self.update_clock) def createButton(self): self.quitButton = Button( self, text='Quit', command=self.quit ) self.quitButton.grid() app = App() app.master.title("Clock Time!") app.mainloop() Regards Karim On 01/12/2011 08:41 PM, Enih Gilead wrote: > Hi, all !
๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ software-development โ€บ threads โ€บ 66698 โ€บ exit-a-tkinter-gui-program
python - Exit a Tkinter GUI Program [SOLVED] | DaniWeb
January 8, 2007 - Also, can you intercept an exit when you use the little x in the title bar, just to affirm that you really want to exit, or you in case you should save data as a file before you exit. ... In Tkinter, quit() and destroy() do different things. quit() stops the currently running Tk event loop (the innermost mainloop or a nested modal loop), returning control to the Python code after mainloop.
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
Disable exit button - Raspberry Pi Forums
I am not sure how to remove the X button but you can stop it doing anything. ... import tkinter as tk def donothing(): pass main = tk.Tk() main.protocol('WM_DELETE_WINDOW',donothing) main.mainloop()