Right Click menu using Tkinter

20 Apr, 2020
Python 3.x comes bundled with the Tkinter module that is useful for making GUI based applications. Of all the other frameworks supported by Python Tkinter is the simplest and fastest. Tkinter offers a plethora of widgets that can be used to build GUI applications along with the main event loop that keeps running in the background until the application is closed manually.
Note: For more information, refer to Python GUI – tkinter
Tkinter provides a mechanism to deal with events. The event is any action that must be handled by a piece of code inside the program. Events include mouse clicks, mouse movements or a keystroke of a user. Tkinter uses event sequences that allow the users to bind events to handlers for each widget.Syntax:
widget.bind(event, handler)
Tkinter widget is capable of capturing a variety of events such as Button, ButtonRelease, Motion, Double-Button, FocusIn, FocusOut, Key and many more. The code in this article basically deals with event handling where a popup menu with various options is displayed as soon as right-click is encountered on the parent widget. The Menu widget of Tkinter is used to implement toplevel, pulldown, and popup menus.
Import tkinter moduleimport tkinterImport tkinter sub-modulefrom tkinter import *Creating the parent widgetroot = Tk()Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.Explanation:The Tk() method creates a blank parent widget with close, maximize, and minimize buttons on the top.Creating the label to be displayedL = Label(root, text="Right-click to display menu", width=40, height=20)Syntax: Label(master, **options)Parameter:master: The parent window (root) acts as the master.options: Label() method supports the following options – text, anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength. Here the text option is used display informative text to the user and width and height specifies the position of the Label Widget in the parent window .Explanation:The Label widget is used to display text or images corresponding to a widget.The text displayed on the screen can further be formatted using the other options available under Label widget.Positioning the labelL.pack()Syntax: pack(options)Parameter:options: The options supported by pack() method are expand, fill and side which are used to position the widget on the parent window. However, pack() method is sued without any options here.Explanation:The pack() method is used to position the child widget in the parent widget.Creating the menum = Menu(root, tearoff=0)Syntax: Menu(master, options)Parameter:master: root is the master or parent widget.options: The options supported by Menu widget are title, tearoff, selectcolor, font, fg, postcommand, relief, image, bg, bd, cursor, activeforeground, activeborderwidth and activebackground. The ‘tearoff’ option is used here.Explanation:The tearoff is used to detach menus from the main window creating floating menus. If tearoff=1, it creates a menu with dotted lines at the top which when clicked the menu tears off the parent window and becomes floating. To restrict the menu in the main window tearoff=0 here.Adding options to the menum.add_command(label="Cut")
m.add_command(label="Copy")
m.add_command(label="Paste")
m.add_command(label="Reload")
m.add_separator()
m.add_command(label="Rename")Syntax: add_command(options)Parameter:options: The options available are label, command, underline and accelerator. The label option is used here to specify names of the menu items.Explanation:The add_command() method adds menu items to the menu. The add_separator() creates a thin line between the menu items.def do_popup(event):
    try:
        m.tk_popup(event.x_root, event.y_root)
    finally:
        m.grab_release()
Syntax: tk_popup(x_root, y_root)Parameter: This procedure posts a menu at a given position on the screen, x_root and y_root is the current mouse position relative to the upper left corner of the screen.Explanation:This method is the event handler. When the event(right click) happens the method is called and the menu appears on the parent widget at the position where the event occurs. The finally block ensures that the grab_release() method releases the event grab.L.bind("<Button-3>", do_popup)Syntax: bind(event, handler)Parameter:event: Here, right click is the event and it is denoted by <Button-3>.handler: The handler is a piece of code that performs some particular task when the event triggered.Explanation:The right mouse button is pressed with the mouse pointer over the widget and this triggers an event which is handled by the event handler( do_popup() function ). The do_popup() function displays the menu.Run the applicationmainloop()Syntax: mainloop()Parameter: Takes no arguments.Explanation:It acts like an infinite loop which keeps the application running until the main window is closed manually.
Import tkinter moduleimport tkinter
import tkinter
Import tkinter sub-modulefrom tkinter import *
from tkinter import *
Creating the parent widgetroot = Tk()Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.Explanation:The Tk() method creates a blank parent widget with close, maximize, and minimize buttons on the top.
root = Tk()
Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.Explanation:The Tk() method creates a blank parent widget with close, maximize, and minimize buttons on the top.
Creating the label to be displayedL = Label(root, text="Right-click to display menu", width=40, height=20)Syntax: Label(master, **options)Parameter:master: The parent window (root) acts as the master.options: Label() method supports the following options – text, anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength. Here the text option is used display informative text to the user and width and height specifies the position of the Label Widget in the parent window .Explanation:The Label widget is used to display text or images corresponding to a widget.The text displayed on the screen can further be formatted using the other options available under Label widget.
L = Label(root, text="Right-click to display menu", width=40, height=20)
Syntax: Label(master, **options)Parameter:
master: The parent window (root) acts as the master.
options: Label() method supports the following options – text, anchor, bg, bitmap, bd, cursor, font, fg, height, width, image, justify, relief, padx, pady, textvariable, underline and wraplength. Here the text option is used display informative text to the user and width and height specifies the position of the Label Widget in the parent window .
Explanation:The Label widget is used to display text or images corresponding to a widget.The text displayed on the screen can further be formatted using the other options available under Label widget.
Positioning the labelL.pack()Syntax: pack(options)Parameter:options: The options supported by pack() method are expand, fill and side which are used to position the widget on the parent window. However, pack() method is sued without any options here.Explanation:The pack() method is used to position the child widget in the parent widget.
L.pack()
Syntax: pack(options)Parameter:
options: The options supported by pack() method are expand, fill and side which are used to position the widget on the parent window. However, pack() method is sued without any options here.
Explanation:The pack() method is used to position the child widget in the parent widget.
Creating the menum = Menu(root, tearoff=0)Syntax: Menu(master, options)Parameter:master: root is the master or parent widget.options: The options supported by Menu widget are title, tearoff, selectcolor, font, fg, postcommand, relief, image, bg, bd, cursor, activeforeground, activeborderwidth and activebackground. The ‘tearoff’ option is used here.Explanation:The tearoff is used to detach menus from the main window creating floating menus. If tearoff=1, it creates a menu with dotted lines at the top which when clicked the menu tears off the parent window and becomes floating. To restrict the menu in the main window tearoff=0 here.
m = Menu(root, tearoff=0)
Syntax: Menu(master, options)Parameter:
master: root is the master or parent widget.
options: The options supported by Menu widget are title, tearoff, selectcolor, font, fg, postcommand, relief, image, bg, bd, cursor, activeforeground, activeborderwidth and activebackground. The ‘tearoff’ option is used here.
Explanation:The tearoff is used to detach menus from the main window creating floating menus. If tearoff=1, it creates a menu with dotted lines at the top which when clicked the menu tears off the parent window and becomes floating. To restrict the menu in the main window tearoff=0 here.
Adding options to the menum.add_command(label="Cut")
m.add_command(label="Copy")
m.add_command(label="Paste")
m.add_command(label="Reload")
m.add_separator()
m.add_command(label="Rename")Syntax: add_command(options)Parameter:options: The options available are label, command, underline and accelerator. The label option is used here to specify names of the menu items.Explanation:The add_command() method adds menu items to the menu. The add_separator() creates a thin line between the menu items.
m.add_command(label="Cut")
m.add_command(label="Copy")
m.add_command(label="Paste")
m.add_command(label="Reload")
m.add_separator()
m.add_command(label="Rename")
Syntax: add_command(options)Parameter:
options: The options available are label, command, underline and accelerator. The label option is used here to specify names of the menu items.
Explanation:The add_command() method adds menu items to the menu. The add_separator() creates a thin line between the menu items.
def do_popup(event):
    try:
        m.tk_popup(event.x_root, event.y_root)
    finally:
        m.grab_release()
Syntax: tk_popup(x_root, y_root)Parameter: This procedure posts a menu at a given position on the screen, x_root and y_root is the current mouse position relative to the upper left corner of the screen.Explanation:This method is the event handler. When the event(right click) happens the method is called and the menu appears on the parent widget at the position where the event occurs. The finally block ensures that the grab_release() method releases the event grab.
def do_popup(event):
    try:
        m.tk_popup(event.x_root, event.y_root)
    finally:
        m.grab_release()

Syntax: tk_popup(x_root, y_root)Parameter: This procedure posts a menu at a given position on the screen, x_root and y_root is the current mouse position relative to the upper left corner of the screen.Explanation:This method is the event handler. When the event(right click) happens the method is called and the menu appears on the parent widget at the position where the event occurs. The finally block ensures that the grab_release() method releases the event grab.
L.bind("<Button-3>", do_popup)Syntax: bind(event, handler)Parameter:event: Here, right click is the event and it is denoted by <Button-3>.handler: The handler is a piece of code that performs some particular task when the event triggered.Explanation:The right mouse button is pressed with the mouse pointer over the widget and this triggers an event which is handled by the event handler( do_popup() function ). The do_popup() function displays the menu.
L.bind("<Button-3>", do_popup)
Syntax: bind(event, handler)Parameter:
event: Here, right click is the event and it is denoted by <Button-3>.
handler: The handler is a piece of code that performs some particular task when the event triggered.
Explanation:The right mouse button is pressed with the mouse pointer over the widget and this triggers an event which is handled by the event handler( do_popup() function ). The do_popup() function displays the menu.
Run the applicationmainloop()Syntax: mainloop()Parameter: Takes no arguments.Explanation:It acts like an infinite loop which keeps the application running until the main window is closed manually.
mainloop()
Syntax: mainloop()Parameter: Takes no arguments.Explanation:It acts like an infinite loop which keeps the application running until the main window is closed manually.
import tkinterfrom tkinter import *  root = Tk()  L = Label(root, text ="Right-click to display menu",          width = 40, height = 20)L.pack()  m = Menu(root, tearoff = 0)m.add_command(label ="Cut")m.add_command(label ="Copy")m.add_command(label ="Paste")m.add_command(label ="Reload")m.add_separator()m.add_command(label ="Rename")  def do_popup(event):    try:        m.tk_popup(event.x_root, event.y_root)    finally:        m.grab_release()  L.bind("<Button-3>", do_popup)  mainloop()
Output
ExplanationWhen a right-click is done on the parent window the popup menu appears and displays a list of choices.
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts