There's a nice @mainthread decorator that lets you define functions that even if you call from a thread will get called from Kivy's UI thread. If you try to modify kivy classes (or possibly just even touch them) from a worker thread your app can and most likely will crash.
from kivy.app import Appfrom kivy.uix.floatlayout import FloatLayoutfrom kivy.lang import Builderimport osimport timeimport threading
Builder.load_string("""<MainScreen>:
BoxLayout: orientation: 'vertical' BoxLayout: Label: id: _Log
#this button's activity should be in it's own thread: Button: text: 'GO' on_release: root.go() """)
class MainScreen(FloatLayout):
###This would be in it's own thread: def WriteFile(self): print 'Hello' print "This shoud be happening in it's own thread" self.ids._Log.text = "This shoud be happening in it's own thread" def go(self): for i in xrange(3): time.sleep(1) self.WriteFile()
class SimpleTest(App): def build(self): return MainScreen()
if __name__ == "__main__": SimpleTest().run()
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.clock import mainthread
import os
import time
import threading
Builder.load_string(
"""
<MainScreen>:
BoxLayout:
orientation: 'vertical'
BoxLayout:
Label:
id: _Log
text: 'test'
#this button's activity should be in it's own thread:
Button:
text: 'GO'
on_release: root.go()
"""
)
class MainScreen(FloatLayout):
def WriteFile(self):
print 'Hello'
self.update_label('starting worker job')
time.sleep(1)
self.update_label('ended worker job')
self.notify_finished()
def go(self):
print 'pressed go'
thread = threading.Thread(target = self.WriteFile)
thread.start()
@mainthread
def notify_finished(self):
print 'job done'
self.ids._Log.color = (200,200,0,255)
@mainthread
def update_label(self, message):
print 'got message request',message
self.ids._Log.text = message
class SimpleTest(App):
def build(self):
return MainScreen()
if __name__ == "__main__":
SimpleTest().run()