Python Tkinter: Creating an exit confirmation dialog
Python Tkinter Dialogs and File Handling: Exercise-2 with Solution
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.
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()
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.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Memory Footprint Of An Object:
import sys x = 'farhadmalik' print(sys.getsizeof(x))
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
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