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?
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()
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.