Python Tkinter: Creating an exit confirmation dialog
Write a Python program using Tkinter, that implements a confirmation dialog that asks the user if they want to save changes before exiting the application.
Sample Solution:
Python Code:
Explanation:
In the exercise above -
- import tkinter as tk - Import the required library for creating the GUI components.
- from tkinter import messagebox – Import messagebox for displaying the information dialog.
- Define a function confirm_exit(): It displays a messagebox with "Confirm Exit" as the title and asks the user whether they want to save changes before exiting. Depending on the user's response, it may call the “save_changes()” function and then close the application using root.destroy().
- Define a function save_changes(): Here we implement logic to save changes. It shows a messagebox with a "Saved" message for demonstration purposes.
- root = tk.Tk() - Create the main Tkinter window.
- exit_button = tk.Button(root, text="Exit", command=confirm_exit) - Create an "Exit" button (exit_button) that, when clicked, calls the “confirm_exit()” function.
- exit_button.pack(padx=20, pady=20) - Use the pack() method to display the button with some padding around it.
- root.mainloop() - The main event loop, root.mainloop(), starts the Tkinter application.
Sample Output:
Flowchart:

Go to:
Previous: Creating a simple information dialog.
Next: Opening a file dialog for file selection.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.