当graphics.py对象到达窗口边缘时关闭窗口

时间:2017-07-03 15:11:02

标签: python zelle-graphics

参考John Zelle's graphics.py,我希望GraphWinCircle对象到达窗口边缘后立即关闭,并且不在视线范围内。

以下代码创建一个圆圈并移动它:

win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
    for i in range(40):       
      c.move(30, 0) #speed=30
      time.sleep(1)
      #c should move until the end of the windows(100), 
win.close() # then windows of title "My Circle" should close immediately

有没有办法做到这一点,而不是使用range并计算其确切数量的步骤'?

1 个答案:

答案 0 :(得分:0)

比较圆圈左侧的x位置与窗口的右侧:

from graphics import *

WIDTH, HEIGHT = 300, 300

RADIUS = 10

SPEED = 30

win = GraphWin("My Circle", WIDTH, HEIGHT)

c = Circle(Point(50, 50), RADIUS)

c.draw(win)

while c.getCenter().x - RADIUS < WIDTH:
    c.move(SPEED, 0)
    time.sleep(1)

win.close() # then windows of title "My Circle" should close immediately

在更快的循环中,我们可能会将RADIUS移动到等式的另一侧,并使WIDTH + RADIUS的新常量。

  

如果它是一个Image对象,你会如何建议最左边的   对象的位置,以将其与窗口的宽度进行比较?

Image对象的工作方式类似,使用它的锚点,而不是中心,并使用其宽度而不是半径:

from graphics import *

WIDTH, HEIGHT = 300, 300

SPEED = 30

win = GraphWin("My Image", WIDTH, HEIGHT)

image = Image(Point(50, 50), "file.gif")

image.draw(win)

image_half_width = image.getWidth() / 2

while image.getAnchor().x - image_half_width < WIDTH:
    image.move(SPEED, 0)
    time.sleep(1)

win.close() # the window of title "My Image" should close immediately