如何使用Zelle的'graphics.py'程序正确创建移动形状的函数?

时间:2015-07-16 00:35:30

标签: python python-3.x

第17号问题。在Zelle的“Programming Python”书籍中,6要求提供一个带有两个参数的函数:'shape'和'newCenter',它将根据鼠标点击提供的新点移动或重新绘制现有对象

如果我在函数“myX”和“myY”中添加两个参数,我已经能够弄清楚如何做到这一点,所以我可以减去move方法的差异。什么是我不知道如何仅使用上面指定的两个参数执行相同的计算。这是我的代码:

def moveTo(shape, newCenter, myX, myY):
    myShape = shape
    myNewX = newCenter.getX()
    myNewY = newCenter.getY()
    myXUpd = myNewX - myX
    myYUpd = myNewY - myY
    myShape.move(myXUpd, myYUpd)
    return myNewX, myNewY

def main():
    win = GraphWin("My Graph Win", 500, 500)
    win.setBackground("white")
    win.setCoords(0, 0, 10, 10)
    Text(Point(5, 8.5), "Please click 10 times.").draw(win)
    myPoint = win.getMouse()
    myX = myPoint.getX()
    myY = myPoint.getY()
    myCircle = Circle(myPoint, 2)
    myCircle.draw(win)

    for x in range(1, 10):
        myNewPoint = win.getMouse()
        myX, myY = moveTo(myCircle, myNewPoint, myX, myY)

    win.close()

此外,关于精简,样式或结构的任何一般提示也受到赞赏,因为我是一个相当新的Python开发人员。

谢谢!

1 个答案:

答案 0 :(得分:0)

我自己想出来了,所以任何人都要经历Zelle" Python Programming"本书可以借鉴我的经验。我只是将X和Y从我传入的形状对象中拉出来,从而节省了自己不得不分别再次传递它们。这是更新的代码,其中一些脂肪被削减。

def moveTo(shape, newCenter):
    oldCenter = shape.getCenter()
    myOldX, myOldY = oldCenter.getX(), oldCenter.getY()
    myNewX, myNewY = newCenter.getX(), newCenter.getY()
    moveX = myNewX - myOldX
    moveY = myNewY - myOldY
    shape.move(moveX, moveY)
    return shape

def main():
    win = GraphWin("My Graph Win", 500, 500)
    win.setBackground("white")
    win.setCoords(0, 0, 10, 10)
    Text(Point(5, 8.5), "Please click 10 times.").draw(win)
    myPoint = win.getMouse()
    myX, myY = myPoint.getX(), myPoint.getY()
    myShape = Circle(myPoint, 2)
    myShape.draw(win)

    for x in range(1, 10):
        newCenter = win.getMouse()
        myShape = moveTo(myShape, newCenter)


    win.close()