Tkinter right-click popup unresponsive on OSX

心不动则不痛 提交于 2021-02-04 19:50:06

问题


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?


回答1:


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()


来源:https://stackoverflow.com/questions/30668425/tkinter-right-click-popup-unresponsive-on-osx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!