问题是修改下面的程序,以便每次连续点击都会在屏幕上绘制一个额外的方块。
这是要修改的程序。
def main():
win = GraphWin()
shape = Rectangle(Point(50,50), Point(70,70))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)
for i in range(10):
p = win.getMouse()
c = shape.getCenter()
dx = p.getX() - c.getX()
dy = p.getY() - c.getY()
shape.move(dx,dy)
win.close()
为了解决这个问题,我使用了clone()函数。这是我的解决方案:
def main():
win = GraphWin()
shape = Rectangle(Point(50,50), Point(70,70))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)
for i in range(10):
p = win.getMouse()
c = shape.getCenter()
dx = p.getX() - c.getX()
dy = p.getY() - c.getY()
pshaw = shape.clone()
pshaw.move(dx, dy)
win.close()
但是,该程序不起作用。我见过的其他解决方案涉及创建一个新的形状,如下所示:为什么我不能使用clone()?
def main():
win = GraphWin()
shape = Rectangle(Point(75,75),Point(125,125))
shape.setOutline('Red')
shape.setFill('Red')
shape.draw(win)
for i in range(5):
p = win.getMouse()
tx = p.getX()-25
ty = p.getY()-25
bx = p.getX()+25
by = p.getY()+25
shape2 = Rectangle(Point(tx,ty),Point(bx,by))
shape2.setOutline('Red')
shape2.setFill('Red')
shape2.draw(win)
ct = Text(Point(100,180),'Click again to quit!')
ct.setStyle('bold')
ct.draw(win)
win.getMouse()
win.close()
main()
为什么clone()在这里不起作用?这不是它的目的吗?从头开始创建新形状的建议解决方案对我来说似乎是多余的。
任何帮助的尝试都非常感谢,我想提前说谢谢:)我的头脑旋转 - 期待向大师们学习!
答案 0 :(得分:0)
您的基于克隆的简单解决方案运行正常,您只需将pshaw.draw(win)
命令停止添加新的矩形到窗口:
from graphics import *
win = GraphWin()
shape = Rectangle(Point(50, 50), Point(70, 70))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)
for _ in range(10):
p = win.getMouse()
c = shape.getCenter()
dx = p.getX() - c.getX()
dy = p.getY() - c.getY()
pshaw = shape.clone()
pshaw.move(dx, dy)
pshaw.draw(win)
win.getMouse()
win.close()