退出Kivy时如何停止线程

时间:2019-11-30 10:28:43

标签: python kivy

我编写了以下代码:

test.py

#-*- coding: utf-8 -*-

import time
from kivy.app import App
from kivy.uix.widget import Widget
import threading

class TextWidget(Widget):
    def __init__(self, **kwargs):
        super(TextWidget, self).__init__(**kwargs)
        self.thread1 = None
        self.thread2 = None
        self.stop_flag = True

    def printTime(self):
        print(time.time())

    def schedule(self,interval, f, wait=True):
        base_time = time.time()
        next_time = 0
        while not self.stop_flag:#接続を切るボタンが押されるまでループ
            self.thread2 = threading.Thread(target=f)
            self.thread2.start()
            if wait:
                self.thread2.join()
            next_time = ((base_time - time.time()) % interval) or interval
            time.sleep(next_time)

    def thread_start(self):
        self.stop_flag=False
        self.thread1 = threading.Thread(target=self.schedule,args=(1.00/200, self.printTime, False))
        self.thread1.start()

    def thread_stop(self):
        if self.thread1:
            self.stop_flag=True
            self.thread1.join()
            self.thread1=None

class TestApp(App):
    def __init__(self, **kwargs):
        super(TestApp, self).__init__(**kwargs)
        self.title = 'test'

if __name__ == '__main__':
    TestApp().run()

test.kv

TextWidget:

<TextWidget>:
    BoxLayout:
        orientation: 'vertical'
        Button:
            text: "thread_start"
            on_press: root.thread_start()
        Button:
            text: "thread_stop"
            on_press: root.thread_stop()

它与线程的“开始”按钮和“停止”按钮一起使用,但是当我按下窗口右上角的“关闭”按钮将其结束时,线程继续保留。

如何关闭窗口并同时关闭线程?

过去的问题似乎很有帮助,但是未编写Widget类,所以我不知道如何模仿它。

How to run a Method on the exit of a kivy app

1 个答案:

答案 0 :(得分:1)

就像上面 John 提到的,守护线程在运行时不会阻止主程序退出。所以,如果主程序被杀死,线程也会被杀死。

有关详细信息,请参阅 this