Python Tkinter,停止线程函数 [英] Python Tkinter, Stop a threading function

查看:33
本文介绍了Python Tkinter,停止线程函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently developing a GUI for a 3D printer and I'm having a problem of how to stop a threading function. I want to be able to click a button that has another function within my GUI that will stop the threading function from sending strings of G-code across the serial port. Currently the function has threading incorporated to allow other functions to be triggered during printing. I would greatly appreciate some advice on how I would incorporate this stop feature.

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

Below is the function that opens a G-code file and sends each line across the serial port.

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

推荐答案

线程不能停止,它们必须自己停止.所以你需要向线程发送一个信号,表明该停止了.这通常通过 Event 完成.

Threads cannot be stopped, they have to stop themselves. So you need to send a signal to the thread that it's time to stop. This is usually done with an 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()

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

Now if you set the event elsewhere in your code:

stop_event.set()

线程会注意到,打破循环并死亡.

The thread will notice that, break the loop and die.

这篇关于Python Tkinter,停止线程函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆