【问题标题】:stuck python while loop卡住python while循环
【发布时间】:2017-08-17 21:44:02
【问题描述】:

我无法让我的 while 循环中断。我试图从起点移动圆圈,直到它到达窗口的边缘。我可以让它移动,但它不会停止移动。我尝试了不同类型的循环,甚至添加了一个中断,但它仍然不会中断:/

from time import *
from graphics import *
from random import *
win = GraphWin("My Program", 500,400)

def MoveRight(circle):
    circle_center = circle.getCenter()
    center_x = circle_center.getX()
    center_y = circle_center.getY()
    circle.draw(win)
    for center_x in range(center_x, 450):
        circle.move(10,0)
        sleep(.15)
    circle_center = circle.getCenter()

my_circle = Circle(Point(200,50), 20)
my_circle.setFill("blue")
MoveRight(my_circle)

编辑: 已解决!

【问题讨论】:

  • 哪个while 循环?注意:从多个模块from ... import * 可能永远不是一个好主意。
  • 您的 for 循环执行 250 次(center_x 的值从 200 到 450),但每一步移动 10 个像素,总共 2500 个像素。也就是说,center_x 不再代表第一步之后圆圈的位置。如果您使用 circle.move(1, 0),它的行为可能更像您的预期。

标签: python-3.x while-loop break


【解决方案1】:

我认为圆的中心在 200 x 轴上。
然后在行:

 for center_x in range(center_x, 450):

center_x 等于 200,200 (center_x) 和 450 之间的范围是 250。
那么这个 for 循环会运行 250 次。

剩下的代码

circle.move(10,0)
sleep(.15)

运行 250 次。所以它将运行 250 次 10 步,2500 步!

要解决您的问题,您应该这样做:

while center_x != 450:
    circle.move(10, 0)
    center_x += 10 # Added this
    sleep(.15)

编辑: 我忘了更新center_x...

(请记住,圆不会停在边缘,它会停在 450。
如果边缘在 450,那么它应该可以工作。)

(圆不会停在450,这个圆的中心会。)

【讨论】:

  • 我试过了,它仍然没有停止;然后我意识到我没有更新 center_x 。一旦我这样做了,一切都会奏效。非常感谢!
  • @RebeccaPhillips 你能把你的答案标记为已解决吗?