在while循环中停止for循环

时间:2016-10-25 06:34:31

标签: python tkinter

我在一个条件运行的while循环中有一个for循环。该按钮更改条件变量,但for循环不会停止。

self.cancel_button = tk.Button(self, text="cancel", command=self.cancel)
self.cancel_button.grid(row=0)

def cancel(self):
    self.break_main = 1

self.break_main = 0
while self.break_main == 0:
    for x in list:
        #do stuff

3 个答案:

答案 0 :(得分:0)

看看是否有效:

self.cancel_button = tk.Button(self, text="cancel", command=self.cancel)
self.cancel_button.grid(row=0)

def cancel(self):
    self.break_main = 1

self.break_main = 0
while True:
    if self.break_main:
        break
    #do stuff

答案 1 :(得分:0)

你试过这样做吗?我不能测试它,因为tkinter总是被我的计算机击中和遗漏,有时它有效,有时它不会。

def cancel(self):
    self.break_main = 1

while True:
    self.cancel_button = tk.Button(self, text="cancel", command=self.cancel)
    self.cancel_button.grid(row=0)
    if self.break_main:
       break

答案 2 :(得分:0)

这就像盯着山羊的内脏来收集一些意义......但这里有一个例子可以做你想要的。你没有发布其他90%的代码,所以很难猜到你哪里出错了。我发布这部分只是为了表明可以编写工作示例,并且他们可以更轻松地回答问题。

try:
    import tkinter
except ImportError:
    import Tkinter as tkinter # python 2

import threading
import time

class Foo(tkinter.Frame):

    def __init__(self, parent):
        tkinter.Frame.__init__(self, parent)
        cancel_button = tkinter.Button(self, text="Stop While", command=self.cancel)
        cancel_button.place(x=50, y=50)
        self.pack(fill=tkinter.BOTH, expand=1)
        self._thread = threading.Thread(target=self.while_thread)
        self._thread.isDaemon()
        self._thread.start()

    def cancel(self):
        self.break_main = 1

    def while_thread(self):
        print("Thread start")
        self.break_main = 0
        while self.break_main == 0:
            time.sleep(.1)
        print("Thread done")


if __name__ == "__main__":
    root = tkinter.Tk()
    root.geometry("250x150+300+300")
    app = Foo(root)
    root.mainloop()
    print("Main Done")