2017-07-03 81 views
0

參照John Zelle's graphics.py,我想GraphWinCircle對象到達窗口邊緣並且看不見之後立即關閉。當graphics.py對象到達窗口的邊緣時關閉窗口

下面的代碼創建一個圓,移動它:

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和計數的「階梯」的確切數字嗎?

回答

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對象將同樣的工作,用它的錨,而不是中心,並利用其半徑的寬度,而不是:

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 
+0

可以在Word表格說明什麼做這行的代碼嗎? '而c.getCenter()。x - RADIUS

+0

@KimSuYu,單詞形式「,而圓的左邊緣(圓的中心x位置小於圓的半徑)位於窗口右邊的左邊(WIDTH),請執行以下操作:「,其中」以下內容「是」通過SPEED單位向右移動圓圈,然後在繼續之前睡一秒「。 – cdlane

+0

然後假定使用了一個Image對象而不是一個Circle對象。 getAnchor()會像getCenter()一樣工作嗎?如果它是一個Image對象,你會如何建議將對象的最左邊位置與窗口的寬度進行比較? –