Python代码在Mac OS X(10.8)上无法正常运行但在Windows 7上运行,为什么?
作者:互联网
我正在使用“使用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()
解决方法:
解
为了使代码在Mac OS X中正常工作,这里必须完成的工作.
更改:
self.canvas.bind("<Button-3>", self.popup)
至:
self.canvas.bind("<Button-2>", self.popup)
Button-3是中间单击按钮,而Button-2是辅助单击按钮.
要使其在Windows中运行,请使用Button-3.
标签:popupmenu,python,tkinter 来源: https://codeday.me/bug/20190901/1780083.html