Python tkinter app adding a right click context menu?
Question: I have a python-tkinter gui app that I've been trying to find some way to add
in some functionality. I was hoping there would be a way to right-click on an
item in the app's listbox area and bring up a context menu. Is tkinter able to
accomplish this? Would I be better off looking into gtk or some other gui-
toolkit?


Answer: Here is an example from [effbot](http://effbot.org/tkinterbook/menu.htm) that
uses the Menu widget to create a "popup menu":

    
    
    from Tkinter import * # Tkinter -> tkinter in Python 3
    
    root = Tk()
    
    def hello():
        print "hello!"
    
    # create a popup menu
    menu = Menu(root, tearoff=0)
    menu.add_command(label="Undo", command=hello)
    menu.add_command(label="Redo", command=hello)
    
    # create a frame
    frame = Frame(root, width=512, height=512)
    frame.pack()
    
    def popup(event):
        menu.post(event.x_root, event.y_root)
    
    # attach popup to frame
    frame.bind("<Button-3>", popup)
    
    root.mainloop()
    

Here is the same example written as a class:

    
    
    import Tkinter as tki # Tkinter -> tkinter in Python 3
    
    class GUI(tki.Tk):
        def __init__(self):
            tki.Tk.__init__(self)
    
            # create a popup menu
            self.aMenu = tki.Menu(self, tearoff=0)
            self.aMenu.add_command(label="Undo", command=self.hello)
            self.aMenu.add_command(label="Redo", command=self.hello)
    
            # create a frame
            self.aFrame = tki.Frame(self, width=512, height=512)
            self.aFrame.pack()
    
            # attach popup to frame
            self.aFrame.bind("<Button-3>", self.popup)
    
        def hello(self):
            print "hello!"
    
        def popup(self, event):
            self.aMenu.post(event.x_root, event.y_root)
    
    gui = GUI()
    gui.mainloop()
    

