0

参考John Zelle 的 graphics.py,我希望在对象到达窗口边缘并且看不见GraphWin之后立即关闭。Circle

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

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和计算其确切的“步数”?

4

1 回答 1

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
于 2017-07-03T22:07:02.993 回答