我正在使用“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()