摆脱不能画到关闭的窗口'错误

时间:2018-02-17 19:00:11

标签: python python-3.x graphics

我有这个程序:

import graphics
import random
window = graphics.GraphWin("Dots", 700, 700)
while True:
  x = random.randint(0, 700)
  y = random.randint(0, 700)
  p = graphics.Point(x, y)
  p.draw(window)
window.close()

代码工作正常;画了很多点,但当我关闭它时按下' x'签名,它显示错误:

  

GraphicsError:无法绘制到关闭的窗口

如何摆脱它让程序停止绘制点并经历常规关闭程序?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,我的解决方法是:

while True:

    try:
        # Code to run
        x = random.randint(0, 700)
        y = random.randint(0, 700)
        p = graphics.Point(x, y)
        p.draw(window)

    except GraphicsError:
        # When the cross is clicked and the exception occurs
        break

win.close()

请注意,此try-except中可能还会捕获其他错误。