Python Tkinter,停止线程函数

ron*_*635 3 python multithreading tkinter function

我目前正在为 3D 打印机开发 GUI,并且遇到如何停止线程函数的问题。我希望能够单击 GUI 中具有另一个功能的按钮,该按钮将阻止线程函数通过串行端口发送 G 代码字符串。目前,该函数已合并线程,以允许在打印期间触发其他函数。我非常感谢有关如何合并此停止功能的一些建议。

下面是打开 G 代码文件并通过串行端口发送每一行的函数。

def printFile():
def callback():
    f = open(entryBox2.get(), 'r');
    for line in f:
        l = line.strip('\r')
        ser.write("<" + l + ">")
        while True:
            response = ser.read()
            if (response == 'a'):
                break
t = threading.Thread(target=callback)
t.start()
Run Code Online (Sandbox Code Playgroud)

Nov*_*vel 6

线程无法停止,它们必须自行停止。因此,您需要向线程发送一个信号,表明该停止了。这通常是通过Event.

stop_event = threading.Event()
def callback():
    f = open(entryBox2.get(), 'r');
    for line in f:
        l = line.strip('\r')
        ser.write("<" + l + ">")
        while True:
            response = ser.read()
            if (response == 'a'):
                break
            if stop_event.is_set():
                break
t = threading.Thread(target=callback)
t.start()
Run Code Online (Sandbox Code Playgroud)

现在,如果您在代码中的其他位置设置该事件:

stop_event.set()
Run Code Online (Sandbox Code Playgroud)

线程会注意到这一点,打破循环并死亡。