Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the most commonly used packages for GUI applications which comes with the Python itself.
Note: For more information, refer to Python GUI – tkinter
Menu Widget
Menus are an important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other top-level windows.
Syntax:
Popup menus are context menus that appear on user interaction. This menu can be shown anywhere on the client window. below is the python code to create a popup menu using Tkinter library.
Python3 1==
#creating popup menu in tkinterimporttkinterclassA:#creates parent windowdef__init__(self):self.root=tkinter.Tk()self.root.geometry('500x500')self.frame1=tkinter.Label(self.root,width=400,height=400,bg='#AAAAAA')self.frame1.pack()#create menudefpopup(self):self.popup_menu=tkinter.Menu(self.root,tearoff=0)self.popup_menu.add_command(label="say hi",command=lambda:self.hey("hi"))self.popup_menu.add_command(label="say hello",command=lambda:self.hey("hello"))self.popup_menu.add_separator()self.popup_menu.add_command(label="say bye",command=lambda:self.hey("bye"))#display menu on right clickdefdo_popup(self,event):try:self.popup_menu.tk_popup(event.x_root,event.y_root)finally:self.popup_menu.grab_release()defhey(self,s):self.frame1.configure(text=s)defrun(self):self.popup()self.root.bind("<Button-3>",self.do_popup)tkinter.mainloop()a=A()a.run()
Output:
The popup menu in above code appears on right-click.
Functions
Menu(root): creates the menu.
add_command(label, command): adds the commands on the menu, the command argument calls the function hey() when that option is clicked.
add_separator(): adds a separator.
tk_popup(x, y): posts the menu at the position given as arguments
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.