Tkinter Messagebox
Message Boxes
A message box is a small window that pops up with a message, like "Your file is saved" or "Something went wrong".
Message boxes are in the messagebox module, which you import like this:
from tkinter import messagebox
Show a Message
Use showinfo() to show a message. The first argument is the title, and the second is the message:
Example
Show a message when the button is clicked:
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.geometry("300x200")
def show():
messagebox.showinfo(
"Info", "Hello, World!")
button = tk.Button(window, text="Show",
command=show)
button.pack()
window.mainloop()
Result:
After clicking the button:
The user closes the message box by clicking OK.
Errors and Warnings
Use showerror() to tell the user that something went wrong:
Example
Show an error message:
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.geometry("300x200")
def show():
messagebox.showerror(
"Error", "Something went wrong!")
button = tk.Button(window, text="Show",
command=show)
button.pack()
window.mainloop()
Result:
After clicking the button:
There is also showwarning(), which works the same way, but shows a warning icon.
Ask a Question
Use askyesno() to ask a question. It returns True if the user clicks Yes, and False if the user clicks No:
Example
Ask the user a question:
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.geometry("300x200")
def ask():
answer = messagebox.askyesno(
"Question", "Do you like Python?")
if answer:
label.config(text="Great!")
else:
label.config(text="Too bad!")
button = tk.Button(window, text="Ask",
command=ask)
button.pack()
label = tk.Label(window)
label.pack()
window.mainloop()
Result:
After clicking Ask:
After clicking Yes:
The code after askyesno() waits until the user has clicked Yes or No.
Note: The buttons in a message box are shown in the language of the user's computer.