Python Tkinter,停止线程函数

编程入门 行业动态 更新时间:2024-10-25 14:27:43
本文介绍了Python Tkinter,停止线程函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我目前正在为 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 07:13:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390795.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   函数   Python   Tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!