问题
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