I'm learing Python using the book "Introduction to Programming Using Python (Pearson 2013)". I use PyCharm 2.7 on my Mac OS X (10.8) to write Pyhon 3 code.
The following code (Create a GUI with tkinter and add a popup menu) does not run properly on my Mac OS X. The problem is that the popup menu doesn't show when pressing the right mouse click. I tested the code on my Windows 7 VM and in Windows 7 it works perfectly.
So my question is: why does the code work on Windows 7 but not on Mac OS X?
Here's the code:
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()
Solution
To make the code work properly in Mac OS X here's what has to be done.
Change:
self.canvas.bind("<Button-3>", self.popup)
To:
self.canvas.bind("<Button-2>", self.popup)
Button-3 is the middle click button while Button-2 is the secondary click button.
To make it work in Windows, use Button-3.