How to create a Popup Menu in Tkinter?



We need menubars in applications where user interaction is required. Menus can be created by initializing the Menu(parent) object along with the menu items. A popup Menu can be created by initializing tk_popup(x_root,y_root, False) which ensures that the menu is visible on the screen. Now, we will add an event which can be triggered through the Mouse Button (Right Click). The grab_release() method sets the mouse button release to unset the popup menu.

Example

#Import the required libraries from tkinter import * from tkinter import ttk #Create an instance of Tkinter frame win = Tk() #Set the geometry of the Tkinter library win.geometry("700x350") label = Label(win, text="Right-click anywhere to display a menu", font= ('Helvetica 18')) label.pack(pady= 40) #Add Menu popup = Menu(win, tearoff=0) #Adding Menu Items popup.add_command(label="New") popup.add_command(label="Edit") popup.add_separator() popup.add_command(label="Save") def menu_popup(event):    # display the popup menu    try:       popup.tk_popup(event.x_root, event.y_root, 0)    finally:       #Release the grab       popup.grab_release() win.bind("<Button-3>", menu_popup) button = ttk.Button(win, text="Quit", command=win.destroy) button.pack() mainloop()

Output

Running the above code will display a window with a Label and a button. When we right click with the Mouse, a popup menu will appear in the window.

Updated on: 2021-05-25T09:20:40+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements