How it works...

First, we instantiate each menu, indicating the parent container. The tearoff option, set to 1 by default, indicates that the menu can be detached by clicking on the dashed line of its top border. This behavior is not applied to the top menu bar, but if we want to deactivate this functionality, we have to set this option to 0:

    def __init__(self):
super().__init__()
menu = tk.Menu(self)
file_menu = tk.Menu(menu, tearoff=0)

Menu entries are arranged in the same order that they are added, using the add_command, add_separator, and add_cascade methods:

menu.add_cascade(label="File", menu=file_menu)
menu.add_command(label="About")
menu.add_command(label="Quit", command=self.destroy)

Usually, add_command is called with a command option, which is the callback invoked when the entry is clicked. There are no arguments passed to the callback function, exactly as with the command option of the Button widget.

For illustration purposes, we only added this option to the Quit entry to destroy the Tk instance and close the application.

Finally, we attach the menu to the top-level window by calling self.config(menu=menu). Note that each top-level window can only have a single menu bar configured.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset