【问题标题】:Check if clicks are within a graphic shape (circle)检查点击是否在图形形状(圆形)内
【发布时间】:2016-03-22 04:58:05
【问题描述】:

我正在使用图形模块参考“graphics.py”

你如何编写一个函数,如果用户在一个圆圈内点击它应该返回 True,否则它应该返回 False。

我什至不确定如何开始。我想测试用户的点击是否在形状内。

【问题讨论】:

    标签: python python-3.x window zelle-graphics


    【解决方案1】:

    使用 getMouse()。这会在用户单击时暂停,然后返回鼠标在窗口中的位置(作为一个点)。 checkMouse() 将返回鼠标的位置,无需单击。

    例如:

    win = GraphWin('Example Window', 100, 100)
    mousePos = win.getMouse()
    

    现在用它来确定用户是否点击了一个圆圈:

    def isClicked(circle, mousePos):
        distance = sqrt(((mousePos.x - circle.x) ** 2) + ((mousePos.y - circle.y) ** 2))
        return distance < circle.radius
    

    这将是你的功能。

    使用该函数的代码示例:

    from graphics import *
    from math import sqrt
    
    def isClicked(circle, mousePos):
        distance = sqrt(((point.x - circle.x) ** 2) + 
                        ((point.y - circle.y) ** 2))
        return distance < circle.radius
    
    def main():
        win = GraphWin('Example Window', 100, 100)
        circle = Circle(Point(50,50), 25)
        circle.setFill('blue')
        circle.draw(win)
        mousePos = win.getMouse()
        if isClicked(circle, mousePos):
            print "You clicked in the circle!"
        else:
            print "You clicked outside the circle!"
    
    main()
    

    【讨论】:

    • 是否有不使用“从数学导入排序”的另一种方法?
    • 您问这个是因为从数学导入时遇到错误吗?检查拼写错误。是 q r t,不是 s o r t。这代表“平方根”。我可能只是空白,但我想不出一种方法来计算一个点是否在圆内而不使用 sqrt 或正弦函数。
    • 此示例代码实际上不起作用。第一个错误是“NameError: global name 'point' is not defined”,因为 isClicked() 的形式参数命名错误。但是解决这个问题,使用当前的 graphics.py 它失败了,“AttributeError:Circle instance has no attribute 'x'”,因为试图获取它没有的 Circle 的'x',而是有一个中心一个“x”。
    【解决方案2】:

    有没有其他不使用“从数学导入排序”的方法?

    从字面上理解您的请求,并修复 Dardar Fishcake 示例中的错误,我们可以这样做:

    from graphics import *
    
    def isClicked(circle, point):
        center = circle.getCenter()
    
        distance = ((point.getX() - center.getX()) ** 2 + (point.getY() - center.getY()) ** 2) ** 0.5
    
        return distance < circle.radius
    
    def main():
        win = GraphWin('Example', 100, 100)
    
        circle = Circle(Point(50, 50), 25)
        circle.setFill('blue')
        circle.draw(win)
    
        while True:
            mousePos = win.getMouse()
    
            if isClicked(circle, mousePos):
                print("You clicked in the circle!")
                break
            else:
                print("You clicked outside the circle!")
    
        win.close()
    
    main()
    

    这里我们用x ** 0.5 替换了sqrt(x)。示例逻辑也略有变化——这个会一直接受点击,直到你点击圆圈。

    【讨论】:

      猜你喜欢
      • 2015-07-20
      • 1970-01-01
      • 2015-07-11
      • 2016-06-01
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多