Tkinter messagebox – Ask Retry or Cancel

Tkinter messagebox – Ask Retry or Cancel

In Tkinter, the messagebox.askretrycancel() method is used to ask if the user would like to retry or cancel an operation with two actions: Retry, Cancel.

Tkinter messagebox – Ask Retry or Cancel in MacOS
Tkinter messagebox – Ask Retry or Cancel – MacOS

If user clicks on Retry button, then askretrycancel() returns True, or else if user clicks on Cancel button, then askretrycancel() returns False. Based on the returned value, we can proceed with the required logic using an if else statement.

In this tutorial, you will learn how to ask a question in a message box using messagebox.askretrycancel() method in Tkinter, with an example program.

Syntax of messagebox.askretrycancel()

The syntax of askretrycancel() method is

messagebox.askretrycancel(title, message)

where

ParameterDescription
titleThis string is displayed as title of the messagebox. [How a title is displayed in message box depends on the Operating System. ]
messageThis string is displayed as a message inside the message box.

Examples

1. Ask if user want to proceed with the operation

For example, consider that you have created a GUI application using Python Tkinter, and you would like to ask the user a question: Do you want to proceed?

You can ask the question with OK or Cancel actions in a messagebox, as shown in the following code.

Python Program

import tkinter as tk
from tkinter import messagebox

# Create the main window
window = tk.Tk()

# Ask for confirmation: OK or Cancel
result = messagebox.askretrycancel("Sample Operation Interrupted", "Do you want to retry?")
if result:
    print("User clicked Retry")
else:
    print("User clicked Cancel")

# Run the application
window.mainloop()

After user takes an action by clicking on either of the buttons, the return value is stored in result variable. Based on this value, we print an output.

Output

In Windows

In MacOS

Tkinter messagebox – Ask Retry or Cancel in MacOS
Tkinter messagebox – Ask Retry or Cancel in MacOS

If user clicks on Retry button, askretrycancel() returns True, and we get the following output in Terminal.

Tkinter askretrycancel() Output - When user clicks on Retry button
Clicks on Retry – Terminal Output

If user clicks on Cancel button, askretrycancel() returns False, and we get the following output in Terminal.

Tkinter askretrycancel() Output - When user clicks on Cancel button
Clicks on Cancel – Terminal Output

Summary

In this Python Tkinter tutorial, we learned how to ask a question with Retry and Cancel actions in a message box in Tkinter, with examples.

Related Tutorials

Code copied to clipboard successfully 👍