Create a Python GUI program to close a window

Python tkinter Basic: Exercise-18 with Solution

Write a Python GUI program to create a window that closes when a "Close" button is clicked.

Sample Solution:

Python Code:

import tkinter as tk

# Function to close the window
def close_window():

# Create the main window
parent = tk.Tk()
parent.title("Close Window Example")

# Create a label
label = tk.Label(parent, text="Click the 'Close' button to close this window.")
label.pack(padx=25, pady=25)

# Create a close button
close_button = tk.Button(parent, text="Close", command=close_window)

# Start the Tkinter event loop


In the exercise above -

  • First we import the 'tkinter' library and create the main window using tk.Tk().
  • Next we define a function called "close_window()" that calls root.destroy() to close the main window.
  • A label and a "Close" button are added to the window. The button's command parameter is set to 'close_window', so clicking the button will execute the "close_window()" function.
  • The program starts the Tkinter event loop using parent.mainloop(), which keeps the GUI window running.

Sample Output:

Tkinter: Create a Python GUI program to close a window. Part-1


Flowchart: Create a Python GUI program to close a window.

Python Code Editor:

Previous: Create interactive tooltips in a Python Tkinter window.
Next: Create a Python Tkinter application with color picker.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Summing a sequence of numbers (calculating the sum of zero to ten with skips):

>>> l = range(0,10,2)
>>> sum(l)


We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook