Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python tKinter多线程停止线程_Python_Multithreading_Tkinter_Python Multithreading - Fatal编程技术网

Python tKinter多线程停止线程

Python tKinter多线程停止线程,python,multithreading,tkinter,python-multithreading,Python,Multithreading,Tkinter,Python Multithreading,我用tKinter创建了一个Python GUI。在我的简单示例中,我有一个按钮,可以触发一个简单循环,使计数器递增。我已经成功地将计数器线程化,这样我的GUI就不会冻结,但是我在让它停止计数方面遇到了问题。这是我的密码: # threading_example.py import threading from threading import Event import time from tkinter import Tk, Button root = Tk() class Contro

我用tKinter创建了一个Python GUI。在我的简单示例中,我有一个按钮,可以触发一个简单循环,使计数器递增。我已经成功地将计数器线程化,这样我的GUI就不会冻结,但是我在让它停止计数方面遇到了问题。这是我的密码:

# threading_example.py
import threading
from threading import Event
import time
from tkinter import Tk, Button


root = Tk()

class Control(object):

    def __init__(self):
        self.my_thread = None
        self.stopThread = False

    def just_wait(self):
        while not self.stopThread:
            for i in range(10000):
                time.sleep(1)
                print(i)

    def button_callback(self):
        self.my_thread = threading.Thread(target=self.just_wait)
        self.my_thread.start()

    def button_callbackStop(self):
        self.stopThread = True
        self.my_thread.join()
        self.my_thread = None


control = Control()
button = Button(root, text='Run long thread.', command=control.button_callback)
button.pack()
button2 = Button(root, text='stop long thread.', command=control.button_callbackStop)
button2.pack()


root.mainloop()

如何安全地使计数器停止递增并优雅地关闭线程?

您必须检查
for
循环中的
self.stopThread
您必须检查
for
循环中的
self.stopThread
,因此您希望for循环和while循环并行运行?他们不能。正如您所拥有的,for循环正在运行,并且不会注意while循环条件

你只需要做一个循环。如果希望线程在10000个周期后自动终止,可以这样做:

def just_wait(self):
    for i in range(10000):
        if self.stopThread:
            break # early termination
        time.sleep(1)
        print(i)

所以你想让for循环和while循环并行运行?他们不能。正如您所拥有的,for循环正在运行,并且不会注意while循环条件

你只需要做一个循环。如果希望线程在10000个周期后自动终止,可以这样做:

def just_wait(self):
    for i in range(10000):
        if self.stopThread:
            break # early termination
        time.sleep(1)
        print(i)

我该怎么做?我该怎么做?嘿,约翰·内森,谢谢,我有个大脑放屁的时刻。嘿,约翰·内森,谢谢,我有个大脑放屁的时刻。