How can I start a thread from a Kivy button?

Viewed 4190

Not sure if anyone can help me with this. I have been unable to find a simple answer to this anywhere.

I am building a GUI in Kivy which shows the webcam feed (using openCV) and has two buttons (Button A and B). When I press Button A, it calls a function which does something. However, my screen and GUI freezes as the called function is executing.

How to I implement the function called by the button press to run on a different thread in python?

2 Answers

If your button calls a function which takes time to execute, kivy window freezes till the function is done. You can use multi threading and have a thread execute that function. I don't have your code but for example:

from threading import Thread

# the function that the button executes
def button_press():
    # create the thread to invoke other_func with arguments (2, 5)
    t = Thread(target=other_func, args=(2, 5))
    # set daemon to true so the thread dies when app is closed
    t.daemon = True
    # start the thread
    t.start()


def other_func(a, b):
    # your code here

In your .kv file you can do:

#:import threading threading
.
.
.
    Button:
        on_release: threading.Thread(target=root.do_something).start()

see threading.

Related