使用异常中断while循环

时间:2012-07-13 23:54:23

标签: python events exception

好吧所以说我有一个Tkinter窗口和一个while循环。 Tkinter窗口在一个单独的线程中运行,而while循环在main中。例如:

  def quit_me():
      raise ValueError("Exception to quit while loop")
      exit()
  root = Tk()
  start_new_thread(root.mainloop,())
  root.protocol("WM_DELETE_WINDOW", quit_me)
  def main():
      while (true):
          try:
              pass #do stuff here
          except ValueError:
              break

这可能吗?我已经在我的应用程序中尝试了它,但它似乎没有工作。有一个更好的方法吗?有什么想法吗?

1 个答案:

答案 0 :(得分:2)

不会跨线程抛出异常。除非你的#do stuff here最终实际调用quit_me()函数,否则你的主线程将永远不会看到抛出的异常。

您可以使用全局执行此操作:

QuitNow = False

def quit_me():
    QuitNow = True

def main():
    while not QuitNow:
        #do stuff here
相关问题