How to do it...
First, we'll have to import the Menu class from tkinter. Add the following line of code to the top of the Python module, where the import statements live:
In line 119, we are calling the constructor of the imported Menu module class and pass in our main GUI instance, win. We save an instance of the Menu object in the menu_bar variable. In line 120, we configure our GUI to use the just created Menu as the menu for our GUI.
In order to make this work, we also have to add the menu to the menu bar and give it a label.
The menu item was already added to the menu, but we still have to add the menu to the menu bar:
GUI_menubar_file.py
Running this code adds a menu bar with a menu that has a menu item:
Next, we'll add a second menu item to the first menu that we added to the menu bar:
Running the code produces the following result:
We can add a separator line between the menu items by adding this line of code in between the existing menu items:
Now, we can see a separator line in between our two menu items:
By passing in the tearoff property to the constructor of the menu, we can remove the first dashed line that, by default, appears above the first menu item in a menu:
Now, the dashed line no longer appears, and our GUI looks so much better:
Next, we'll add a second menu, which will be horizontally placed to the right of the first menu. We'll give it one menu item, which we name About and, in order for this to work, we have to add this second menu to the menu bar.
File and Help | About are very common Windows GUI layouts we are all familiar with, and we can create those same menus using Python and tkinter:
GUI_menubar_help.py
Now, we have a second menu with a menu item in the menu bar:
At this point, our GUI has a menu bar and two menus that contain some menu items. Clicking on them does not do much until we add some commands. That's what we will do next. Add the following code above the creation of the menu bar:
Next, we'll bind the File | Exit menu item to this function by adding the following command to the menu item:
Now, when we click the Exit menu item, our application will indeed exit.