我正在使用“使用Python编程简介(Pearson 2013)”一书学习Python。我在Mac OS X(10.8)上使用PyCharm 2.7来编写Pyhon 3代码。
以下代码(使用tkinter创建GUI并添加弹出菜单)在Mac OS X上无法正常运行。问题是按下鼠标右键时弹出菜单不显示。我在Windows 7 VM和Windows 7上测试了代码,它运行得很好。
所以我的问题是:为什么代码适用于Windows 7但不适用于Mac OS X?
以下是代码:
from tkinter import *
class PopupMenuDemo:
def __init__(self):
window = Tk()
window.title("Popup Menu Demo")
# Create a popup menu
self.menu = Menu(window, tearoff = 0)
self.menu.add_command(label = "Draw a line", command = self.displayLine)
self.menu.add_command(label = "Draw an oval", command = self.displayOval)
self.menu.add_command(label = "Draw a rectangle", command = self.displayRectangle)
self.menu.add_command(label = "Clear", command = self.clearCanvas)
# Place canvas in window
self.canvas = Canvas(window, width = 200, height = 100, bg = "white")
self.canvas.pack()
# Bind popup to canvas
self.canvas.bind("<Button-3>", self.popup)
window.mainloop()
# Display a rectangle
def displayRectangle(self):
self.canvas.create_rectangle(10, 10, 190, 90, tags = "rectangle")
def displayOval(self):
self.canvas.create_oval(10, 10, 190, 90, tags = "oval")
def displayLine(self):
self.canvas.create_line(10, 10, 190, 90, tags = "line")
self.canvas.create_line(10, 90, 190, 10, tags = "line")
def clearCanvas(self):
self.canvas.delete("rectangle", "oval", "line")
def popup(self, event):
self.menu.post(event.x_root, event.y_root)
PopupMenuDemo()
答案 0 :(得分:5)
<强>解决方案强>
为了使代码在Mac OS X中正常运行,必须完成这项工作。
变化:
self.canvas.bind("<Button-3>", self.popup)
要:
self.canvas.bind("<Button-2>", self.popup)
Button-3是中键单击按钮,而Button-2是辅助单击按钮。
要使其在Windows中运行,请使用Button-3。