Search code examples
androidpythoncross-platformkivykivy-language

Button on Floatlayout is Not working while executing code in kivy


I have two buttons on floatlayout both has on_press() event

    Button:
        id: button1
        size_hint: .12,.12
        pos_hint:{"center_x":.30,"center_y":.065}
        on_press: root.speeak(textbox2.text)
    Button:
        id: button2
        size_hint: .12,.12
        #pos_hint:{"center_x":.50,"center_y":.065}
        on_press: root.stop()

Method behind the buttons

 def speeak(self,texts):
    self.texts = texts
    global speak
    speak = wincl.Dispatch("SAPI.SpVoice")
    speak.Speak(self.texts)

def stop(self,*args):
    speak.Pause()

When I press button1 whole layout hang and stop button not work. Someone has any Idea for this problem


Solution

  • This is because the code blocks at speak.Speak(self.texts) and you won't be able to pause or do anything until that line is done. One way of solving this is to use multithreading and use a thread to run speak.Speak(self.texts) so your main loop doesn't get affected. Here is an example you can start with:

    import threading
    
    def speeak(self, texts):
        self.texts = texts
        self.speak = wincl.Dispatch("SAPI.SpVoice")
        t = threading.Thread(target=self.speakStart, args=(self.texts,))
        t.daemon = True
        t.start()
    
    def speakStart(self, text):
        self.speak.Speak(text)
    
    def stop(self):
        self.speak.Pause()