您只需要获取返回的点win.getMouse()
并确保 x 和 y 值在范围内。我在inside
函数下面执行此操作,然后使用此布尔值在窗口上显示“y”或“n”
from graphics import *
def inside(test_Point, P1, P2):
'''
determines if the test_Point is inside
the rectangle with P1 and P2 at opposite corners
assumes P1 is upper left and P2 is lower right
'''
tX = test_Point.getX()
tY = test_Point.getY()
# first the x value must be in bounds
t1 = (P1.getX() <= tX) and (tX <= P2.getX())
if not t1:
return False
else:
return (P2.getY() <= tY) and (tY <= P1.getY())
win = GraphWin("Box", 600, 600)
yes_box = Rectangle(Point(200, 150), Point(350, 50))
yes_box.setOutline('blue')
yes_box.setWidth(1)
yes_box.draw(win)
# where was the mouse clicked?
t = win.getMouse()
# is that inside the box?
if inside(t, yes_box.getP1(), yes_box.getP2()):
text = 'y'
else:
text = 'n'
# draw the 'y' or 'n' on the screen
testText = Text(Point(200,300), text)
testText.draw(win)
exitText = Text(Point(200,350), 'Click anywhere to quit')
exitText.draw(win)
win.getMouse()
win.close()