Python Tkinter,停止线程函数

Python Tkinter,停止线程函数,python,multithreading,function,tkinter,Python,Multithreading,Function,Tkinter,我目前正在为3D打印机开发GUI,我遇到了一个如何停止线程功能的问题。我希望能够单击一个按钮,该按钮在我的GUI中具有另一个功能,可以阻止线程功能通过串行端口发送G代码字符串。目前,该功能已合并线程,以允许在打印期间触发其他功能。我将非常感谢一些建议,我将如何纳入这个停止功能 下面是打开G代码文件并通过串行端口发送每一行的函数 def printFile(): def callback(): f = open(entryBox2.get(), 'r'); for line in

我目前正在为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()
def printFile():
def callback():
f=打开(entryBox2.get(),'r');
对于f中的行:
l=行.strip('\r')
顺序写(“”)
尽管如此:
response=ser.read()
如果(响应='a'):
打破
线程(目标=回调)
t、 开始()

线程无法停止,它们必须自行停止。因此,您需要向线程发送一个信号,该停止了。这通常通过
事件
完成

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()

螺纹会注意到,断开环并进行模具加工

使用全局变量作为线程停止的条件

send_gcode = True

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

def printFile():
    def print_thread():
        f = open(entryBox2.get(), 'r');
        for line in f:
            if not send_gcode:
                break
            l = line.strip('\r')
            ser.write("<" + l + ">")
            while True:
                response = ser.read()
                if (response == 'a'):
                    break
    t = threading.Thread(target=print_thread)
    send_gcode = True
    t.start()
def stop_callback(event):
    global send_gcode
    send_gcode = False