检查单击是否在图形对象内[Python图形模块]
以下是我正在使用的模块: 我想看看用户的点击是否在一个形状内。我使用了in运算符,但我知道这是不正确的。下面是我的一段代码:检查单击是否在图形对象内[Python图形模块],python,python-3.x,graphics,click,window,Python,Python 3.x,Graphics,Click,Window,以下是我正在使用的模块: 我想看看用户的点击是否在一个形状内。我使用了in运算符,但我知道这是不正确的。下面是我的一段代码: win = GraphWin("Click Speed", 700, 700) theTarget = drawTarget(win, random.randrange(0,685), random.randrange(0,685)) while theTarget in win: click = win.getMouse() if click in
win = GraphWin("Click Speed", 700, 700)
theTarget = drawTarget(win, random.randrange(0,685), random.randrange(0,685))
while theTarget in win:
click = win.getMouse()
if click in theTarget:
print("Good job")
我省略了绘制目标形状的代码,因为它很长而且不必要这是一个移动的圆圈。
我使用的是while循环,因此它允许我不断地获得用户的点击
如何使用getMouse()命令检查用户的单击是否处于指定的目标形状
我将来将不得不使用它来制作更抽象的形状(而不是简单的圆)。圆
对于圆的简单情况,可以使用距离公式确定鼠标是否在内部。例如:
#检查pt1是否在circ中
def内循环(pt1,循环):
#使用
#距离公式
dx=pt1.getX()-circ.getCenter().getX()
dy=pt1.getY()-circ.getCenter().getY()
dist=math.sqrt(dx*dx+dy*dy)
#检查距离是否小于半径
返回区
def inOval(pt1, oval):
# get the radii
rx = abs(oval.getP1().getX() - oval.getP2().getX())/2
ry = abs(oval.getP1().getY() - oval.getP2().getY())/2
# get the center
h = oval.getCenter().getX()
k = oval.getCenter().getY()
# get the point
x = pt1.getX()
y = pt1.getY()
# use the formula
return (x-h)**2/rx**2 + (y-k)**2/ry**2 <= 1
def inPoly(pt1, poly):
points = poly.getPoints()
nvert = len(points) #the number of vertices in the polygon
#get x and y of pt1
x = pt1.getX()
y = pt1.getY()
# I don't know why this works
# See the link I provided for details
result = False
for i in range(nvert):
# note: points[-1] will give you the last element
# convenient!
j = i - 1
#get x and y of vertex at index i
vix = points[i].getX()
viy = points[i].getY()
#get x and y of vertex at index j
vjx = points[j].getX()
vjy = points[j].getY()
if (viy > y) != (vjy > y) and (x < (vjx - vix) * (y - viy) / (vjy - viy) + vix):
result = not result
return result