Tkinter Menu Create Toolbar
In the previous chapters you have learned to use a series of similar commands to form a menu. Another important concept in window programming is to form toolbars with frequently used commands and place them inside the window for easy access. tkinter does not provide a Toolbar module, but we can use Frame to create toolbars.
Example#1
This program creates a File menu with the Exit command inside the menu. The program also creates a toolbar with an exitBtn button. The program can be terminated either by executing the Exit command in the File menu or by clicking the exitBtn button in the toolbar.
from tkinter import *
root = Tk()
root.title("apidemos.com")
root.geometry("300x180")
menubar = Menu(root) # Create top-level menu
# Create a menu category object and name this menu category File
filemenu = Menu(menubar,tearoff=False)
menubar.add_cascade(label="File",menu=filemenu)
# Create a menu list within the File menuExit
filemenu.add_command(label="Exit",command=root.destroy)
# Create Toolbar
toolbar = Frame(root,relief=RAISED,borderwidth=3)
# Create a button in the toolbar
myGif = PhotoImage(file="apidemos.png")
exitBtn = Button(toolbar,image=myGif,command=root.destroy)
exitBtn.pack(side=LEFT,padx=3,pady=3) # Pack button
toolbar.pack(side=TOP,fill=X) # Pack toolbar
root.config(menu=menubar) # Show menu objects
root.mainloop()
Output:
In fact, all the concepts used in this program have already been learned, and the basic steps are as follows.
(1) Lines 8 to 13, create the File menu.
(2) Line 13, create the Exit command in the File menu, set command=root.destroy.
(3) Line 16, create toolbar toolbar.
(4) Lines 19 and 20 create and wrap the exitBtn button inside the toolbar toolbar.
(5) Line 21 wraps the toolbar.
(6) Line 22 shows the menu.
Of course, the above program also has the disadvantage that the toolbar is too tall. This is because the image in GIF format is too large, and the reader can simply shrink the image in GIF format when designing similar programs.