当 graphics.py 对象到达 window 的边缘时关闭 window

Close window when graphics.py object has reached the edge of window

关于 John Zelle's graphics.py,我希望 GraphWinCircle 物体到达 window 的边缘并且看不见之后立即关闭。

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

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 并计算其 'steps' 的确切数量吗?

比较圆左侧的 x 位置与 window 右侧的 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

If it was an Image object, how would you suggest to get the leftmost position of the object to compare it to the width of the window?

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