Now, let's complete the code for the About and Help menus. The functionality is simple. When a user clicks on the Help or About menu, a message window pops up and waits for the user to respond by clicking on a button. Though we can easily code new Toplevel windows to show the About and Help messages, we will instead use a module called messagebox to achieve this functionality.
The messagebox module provides ready-made message boxes to display a wide variety of messages in applications. The functions available through this module include showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, askyesnocancel, and askretrycancel, as shown in the following screenshot:
To use this module, we simply import it into the current namespace by using the following command:
import tkinter.messagebox
A demonstration of the commonly used functions of messagebox is provided in 2.08.py in the code bundle. The following are some common usage patterns:
import tkinter.messagebox as tmb tmb.showinfo(title="Show Info", message="This is FYI") tmb.showwarning(title="Show Warning", message="Don't be silly") tmb.showerror(title="Show Error", message="It leaked") tmb.askquestion(title="Ask Question", message="Can you read this?") tmb.askokcancel(title="Ask OK Cancel", message="Say Ok or Cancel?") tmb.askyesno(title="Ask Yes-No", message="Say yes or no?") tmb.askyesnocancel(title="Yes-No-Cancel", message="Say yes no cancel") tmb.askretrycancel(title="Ask Retry Cancel", message="Retry or what?")
Equipped with an understanding of the messagebox module, let's code the about and help functions for the code editor. The functionality is simple. When a user clicks on the About or Help menu item, a showinfomessagebox pops up.
To achieve this, include the following code in the editor (2.09.py):
def display_about_messagebox(event=None): tkinter.messagebox.showinfo("About", "{}{}".format(PROGRAM_NAME, "\nTkinter GUI Application\n Development Blueprints"))
Next, we will add the quit confirmation feature. Ideally, we should have implemented file saving in the event the text content has been modified, but for the sake of simplicity I am not putting in that logic here and instead am displaying a prompt for the user to determine whether the program should be closed or kept open. Accordingly, when the user clicks on File | Exit, it prompts an Ok-Cancel dialog to confirm the quit action:
def exit_editor(event=None): if tkinter.messagebox.askokcancel("Quit?", "Really quit?"): root.destroy()
Then, we override the Close button and redirect it to the exit_editor function that we previously defined, as follows:
root.protocol('WM_DELETE_WINDOW', exit_editor)
Then, we add a callback command for all the individual menu items, as follows: