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:
menu = Menu(master, **options)
Note: For more information, refer to Python | Menu widget in Tkinter
Popup Menu
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.
import tkinter
class A:
def __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()
def popup( 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" ))
def do_popup( self ,event):
try :
self .popup_menu.tk_popup(event.x_root,
event.y_root)
finally :
self .popup_menu.grab_release()
def hey( self ,s):
self .frame1.configure(text = s)
def run( 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
- grab_release(): releases the event grab
- bind(key, event): binds the mouse event.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Mar, 2020
Like Article
Save Article