5

I have been looking for a way to display a right-click popup menu on OSX. So far all of my attempts have been unsuccessful. The same code will work fine on a Linux VM(Ubuntu).

For arguments sake I copied the code written in these two pages and tried to run them on my machine.

tkinter app adding a right click context menu?

http://effbot.org/zone/tkinter-popup-menu.htm

Neither have worked in the way I expect them to on OSX but they do when I run them on an Ubuntu VM.

The machine I am using is a Mac Mini4,1 running OSX 10.6.8. Has anyone else experienced this and is there a viable workaround?

Community
  • 1
  • 1
user50083
  • 77
  • 2
  • 8

2 Answers2

10

For odd historical reasons, the right button is button 2 on the Mac, but 3 on unix and windows.

Here is an example that works on my OSX box:

try:
    # python 2.x
    import Tkinter as tk
except ImportError:
    # python 3.x
    import tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        self.popupMenu = tk.Menu(self, tearoff=0)
        self.popupMenu.add_command(label="One", command=self.menu_one)
        self.popupMenu.add_command(label="Two", command=self.menu_two)
        self.popupMenu.add_command(label="Three", command=self.menu_three)

        self.bind("<Button-2>", self.popup)

    def menu_one(self):
        print "one..."

    def menu_two(self):
        print "two..."

    def menu_three(self):
        print "three..."

    def popup(self, event):
        self.popupMenu.post(event.x_root, event.y_root)

if __name__ == "__main__":
    root =tk.Tk()
    frame = Example(root, width=200, height=200)
    frame.pack(fill="both", expand=True)
    root.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • On Mac OSX (and possibly other platforms), you need to add `self.config(menu=self.popupMenu)` for this to work. – Thomas Antony Apr 25 '17 at 17:44
  • @ThomasAntony: no, that won't do anything except throw an error. In this case `self` is a frame, and frames don't have a `menu` option. . Besides, the question is about a context-sensitive ("right-click") menu, not a menubar. – Bryan Oakley Apr 25 '17 at 18:47
  • Another thing is that the window has to be focused for `post` to work. – Thomas Antony Apr 26 '17 at 02:21
  • @ThomasAntony: That is only true for the buggy version of python that ships with OSX. There are better versions that don't have that limitation. – Bryan Oakley Apr 26 '17 at 02:38
1

Because of the MacOS's mouse button index is different from Windows or Linux .You can try this in your code:

MAC_OS = False
    if sys.platform == 'darwin':
MAC_OS = True
if MAC_OS:
    self.bind('<Button-2>', self.context_popup)
else:
    self.bind('<Button-3>', self.context_popup)