Kivy: Starting and Stopping Threads When Button is Clicked

风格不统一 提交于 2020-01-15 15:43:09

问题


I'm having trouble with the threading in Python and Kivy. I'm trying to implement threading in my kivy app. Basically, when I click a button and the screen switches to the next one, I want to launch a thread, and when I click the 'back' button, the thread should stop. It's a pretty simple task, but my current code doesn't end the thread once I pressed 'back'.

Here is my code. I'm only including the necessary parts:

KV:

<MenuScreen>:
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'bgpics/blackboard.png'
FloatLayout:
    Button: #THIS IS the button that should start the thread
        text: "Learn" 
        background_normal:'bgpics/chalk1.png'
        color: 1, 1, 1, 1
        size_hint: .2, .2
        font_name: 'fonts/SqueakyChalkSound.ttf'
        font_size: '40sp'
        pos_hint:{"x":.09,"y":.3}
        size_hint: .4, .4
        on_press: root.manager.current = 'learncategories'

<LearnScreen>:
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'bgpics/categorybg.jpg'
    Button: #THIS IS the button that should stop the thread
        text: "BACK"
        background_normal:'bgpics/yepaint.png'
        color: 0, 0, 0, 1
        font_size: '35sp'
        font_name: 'fonts/DK Lemon Yellow Sun.otf'
        pos: 50, 5
        size_hint: .27, .27
        on_press: root.manager.current = 'menu'

Python:

class Identifier:        
    def start_thread(self):
        thread1=threading.Thread(target=self.serialtest)
        thread1.start()
        thread1.join()

    def serialtest(self):
        lol=1
        while (lol>0):
            print lol
            lol+=1

    def serialstop (self):
        thread1.kill()

class LearnScreen(Screen):
    def on_enter(self):
        Identifier().start_thread()
    def identify(self):
        self.lol=Identifier()
    def quitscreen(self):
        self.identify.serialstop()

来源:https://stackoverflow.com/questions/57786565/kivy-starting-and-stopping-threads-when-button-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!