Tkinter MessageBox

Message Boxes are the most common way in GUI applications to display messages to the user. In Tkinter, the messagebox module provides eight such functions that allow the developers to integrate message boxes in GUI applications.

We will discuss all these functions in great detail with relevant code examples.

Let’s look at the syntax of the tkinter messagebox.

Tkinter MessageBox Syntax :

from tkinter import messagebox
m = messagebox.function(title, message [, options])

Parameters Explanation :

  • Function: It is the name of a function represents a suitable messagebox.
  • Title: It is the title shown at the top of the messagebox.
  • Message: It is the main message that is shown to the user.
  • Options: These are the various options to customize the messagebox.

Real-World Example :

Suppose you are making a GUI application for students where they can check their test results. Here are the requirements :

  • A student will enter his/her name in the entry widget.
  • If the name is the incorrect error message box will be shown.
  • If the name is correct and the student passes his/her test then an info message box with the “Congratulations” message will be shown.
  • If the student fails in his/her test then the warning message box will be shown.
  • Then there will be an exit button that will show a question message box asking users for their confirmation.

Here is the code with proper comments.

from tkinter import *
from tkinter import messagebox

window = Tk() # Create a tkinter window
window.title("Check Result") # Set the title

# Just assume that it came from a database
DATABASE = [("alex","fail"),("john","pass")]

def check_result():
    """Function to check result"""
    for i in DATABASE: # Loop through database
        if i[0] == entry.get():
            # If entry text matches with any name in database
            # Check if student is pass or fail
            if i[1] == "pass":
                # Show congratulation
                messagebox.showinfo("Info",f"Congratulation {i[0]}, You have passed")
            else:
                messagebox.showwarning("Info",f"Sorry {i[0]}, You have failed.")
            return # Finally return from function

    # This will execute if we didnt found the name in database
    # Show a error message
    messagebox.showerror("Error","You Have Entered Invalid Name")

def exit():
    """Function that will ask for user confirmation for exit"""
    confirmation = messagebox.askquestion("Confirm","Are you sure you want to exit.")
    if confirmation:
        quit()


entry = Entry(window) # Entry to ask for student name
entry.pack()
 # Button to check result
Button(window,text = "Check Result",command = check_result).pack()
Button(window,text = "Exit",command = exit).pack() # Exit program

window.mainloop()

Here is the output of the above code.

tkinter messagebox real world example code output.

Tkinter MessageBox Types:

Now let’s look at all types of tkinter messageboxes that are available to us.

1) Information Message Boxes

These are the type of message boxes that allows us to display some important information to the user. Here is the code for that.

a) messagebox.showinfo()

from tkinter import *
from tkinter import messagebox

window = Tk()

messagebox.showinfo("Important Info","This is the important info")

window.mainloop()
Output :
Information Tkinter Messagebox output.

2) Warning Message Boxes

These are the types of message boxes that show some warning or errors to the users.

a) messagebox.showwarning()

It shows a warning to user. here is the code.

from tkinter import *
from tkinter import messagebox

window = Tk()

messagebox.showwarning("Warning","Some Serious Warning.")  

window.mainloop()
Output :
Tkinter waring messagebox code example

b) messagebox.showerror()

This messagebox allows to show an error to the user.

from tkinter import *
from tkinter import messagebox

window = Tk()

messagebox.showerror("Error","A Serious Error")

window.mainloop()
Output :
error box code example output.

3) Question Message Boxes

These are the type of message boxes that asks some “Yes/No” questions to the user and perform actions accordingly.

a) messagebox.askyesnocancel()

This messagebox asks the yes/no/cancel question to the user.

  • If user clicks “yes” then True is returned.
  • If user clicks “no” then False is returned.
  • if user clicks “cancel” then None is returned.

Here is the code example.

from tkinter import *
from tkinter import messagebox

window = Tk()

answer = messagebox.askyesnocancel("Question","Are you Sure?")
print("User has entered : ",answer)
window.mainloop()
Output :
Tkinter error yes/no/cancel code example

b) messagebox.askquestion()

This messagebox asks the yes no question to the user.

from tkinter import *
from tkinter import messagebox

window = Tk()

answer = messagebox.askquestion("Question","Do you love coffee?")
print("User has entered : ",answer)
window.mainloop()
Output :
yes/no questionbox  example output.

c) messagebox.askokcancel()

This messagebox asks okay/ cancel question to the user.

from tkinter import *
from tkinter import messagebox

window = Tk()

answer = messagebox.askokcancel("Question","Do you want to quit?")
print("User has entered : ",answer)
window.mainloop()
Output :
okay/cancel questionbox  example output.

d) messagebox.askretrycancel()

This message box is used when an error occurs inside the application and we ask the user if he wants to retry again or not. Consider the below code example.

from tkinter import *
from tkinter import messagebox

window = Tk()

answer = messagebox.askretrycancel("Error","Internal Server Error!. Do you want to Try Again?")
print("User has entered : ",answer)
window.mainloop()
Output :
retry/cancel questionbox  example output.

That’s wrap for this tutorial.

Leave a Reply