Tkinter Menu add_checkbutton
In the design of the menu list, you can also use the checkbutton to represent the command, also known as the check menu button, the following program example will be used to explain.
Example#1 When the program example is executed, you can see the status bar at the bottom of the window, and the Status in the View menu is actually the checkbox command used.
The above working principle is that when Status is True, there will be a check mark on the left side of Status, and there will be a status bar at the bottom of the window, please refer to the left picture above. When Status is False, there is no check mark on the left side, and there is no status bar at the bottom of the window, refer to the right figure above. check menu button works the same as Widget object Checkbutton, click to switch the status to True or False.
Example#1
Designed to show the status bar when Status is True and hide the status bar when Status is False, the status bar of this program is handled in the label Label way, which can be referred to lines 30 to 34.
from tkinter import *
def status():
if demoStatus.get():
statusLabel.pack(side=BOTTOM,fill=X)
else:
statusLabel.pack_forget() # Hide tab status bar
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 as File
filemenu = Menu(menubar,tearoff=False)
menubar.add_cascade(label="File",menu=filemenu)
# Create a menu list within the File menu Exit
filemenu.add_command(label="Exit",command=root.destroy)
# Create a menu category object and name this menu category as View
viewmenu = Menu(menubar,tearoff=False)
menubar.add_cascade(label="View",menu=viewmenu)
# Create Check menu button inside View menu
demoStatus = BooleanVar()
demoStatus.set(True)
viewmenu.add_checkbutton(label="Status",command=status,
variable=demoStatus) # The status function will be called when the demoStatus status changes.
root.config(menu=menubar)
statusVar = StringVar()
statusVar.set("Show")
statusLabel = Label(root,textvariable=statusVar,relief="raised")
statusLabel.pack(side=BOTTOM,fill=X)
root.mainloop()
Output:
The focus of the above program is as follows, lines 26 to 27 in the View menu using add_checkbutton( ) to create a Check menu button, the object name is Status, while using the demoStatus Boolean variable to record the current status is True or False, this Status object when there is a status change will The status object will execute the status( ) method when there is a status change.
If the current demoStatus is True, execute line 6 of the status( ) method, which is equivalent to displaying the statusLabel. can hide the label status bar.