Tkinter Menu Create pop-up menu
When using the Windows operating system, you can click the right mouse button on the desktop, at this time will pop up a menu, which is a pop-up menu Popup menu, some people will call this menu shortcut menu.
Design this type of menu with the previous need to establish a menu category in the window menubar area has some differences, the establishment of a good Menu object, you can directly use this object to create a list of instructions, and then finally click the right mouse button operation binding to display the pop-up menu can be.
popupmenu = Menu(root, tearoff=False) # Hide dashed dividers
popupmenu.add_command(label = "xx", command = "yy") # Create command list
...
root.bind("<Button-3>", callback) # Binding right mouse click to show popup menu
Example#1
Design pop-up menu, this pop-up menu has two sub-menus, one is Minimize can shrink the window into an icon, and the other is Exit to end the program.
from tkinter import *
from tkinter import messagebox
def minimizeIcon(): # Shrink window to icon
print("Window minimization...")
root.iconify() # Minimize window
def showPopupMenu(event): # Show pop-up window
print("Window popup...")
popupmenu.post(event.x_root,event.y_root) # This menu pops up at the mouse cursor position
# print(event.x_root," *** ",event.y_root)
# print(type(event.x_root)," *** ",type(event.y_root)) # int type
# popupmenu.post(100,100) ############ # Window fixed display
root = Tk()
root.title("apidemos.com")
root.geometry("300x180")
popupmenu = Menu(root,tearoff=False) # Create a pop-up window object
# Create two command lists in the pop-up menu
popupmenu.add_command(label="Minimize",command=minimizeIcon)
popupmenu.add_command(label="Exit",command=root.destroy)
# Click on the right mouse button binding to display the pop-up menu
root.bind("<Button-3>",showPopupMenu)
# root.config(menu=popupmenu) # This code fixes the popupmenu object to the window menu bar
root.mainloop()
Output:
The iconify() in line 6 above minimizes the window, and the post( ) method in line 9 is started by the popupmenu object, which is equivalent to being able to popup this menu at the mouse cursor position (event.x_root,event.y_root).