Applications generally need to show system dialogs to alert the user to events. In this post, we will cover the yes or no dialog, a warning dialog, information dialog, and an error dialog. Tk uses system calls to show dialogs that are native to the underlying platform. Therefore, dialogs on Windows will look like they should on Windows while Mac OS X dialogs will appear correct for that platform.
The askyesno is a dialog that is used to present a user with a yes or no choice. It returns a boolean to the caller.
result = askyesno('Yes No Demo', 'Click on either yes or no')
You use showwarning when you want to warn the user about something.
showwarning('Warning Demo', 'You have been warned')
This dialog is used to supply the user with information.
showinfo('Info Demo', 'This is some information')
You should use showerror when you need to report an error to the user.
showerror('Error Demo', 'This is an error')
Putting it Together
Standard dialog calls are a useful way to notify the user about something important. Since they block the program’s execution, the user is forced to interact with the dialog. This makes the dialogs ideal for forcing the user to read a message or make a choice. Below is a complete program that demonstrates all of the dialogs.
from tkinter import * from tkinter.messagebox import * def ask_yes_no_demo(): result = askyesno('Yes No Demo', 'Click on either yes or no') if result: showinfo('Result', 'You clicked on Yes') else: showinfo('Result', 'You clicked on No') def warning_demo(): showwarning('Warning Demo', 'You have been warned') def info_demo(): showinfo('Info Demo', 'This is some information') def error_demo(): showerror('Error Demo', 'This is an error') root = Tk() Button(text='Ask Yes No', command=ask_yes_no_demo).pack(fill=X) Button(text='Warning', command=warning_demo).pack(fill=X) Button(text='Info', command=info_demo).pack(fill=X) Button(text='Error', command=error_demo).pack(fill=X) Button(text='Quit', command=(lambda: sys.exit(0))).pack(fill=X) mainloop()