如何从Kivy按钮启动一个线程?

4

不确定是否有人能帮我解决这个问题。我一直无法在任何地方找到简单的答案。

我正在使用Kivy构建一个GUI,它显示网络摄像头的视频(使用openCV),并有两个按钮(按钮A和B)。当我按下按钮A时,它调用一个函数执行某些操作。但是,我的屏幕和GUI会冻结,因为调用的函数正在执行。

如何在Python中实现通过按钮按下调用的函数在不同的线程上运行?


1
请提供一个 [mcve]。 - eyllanesc
2个回答

8
如果您的按钮调用一个需要一段时间才能执行的函数,kivy窗口会冻结直到该函数完成。您可以使用多线程并让一个线程执行该函数。我没有您的代码,但是举个例子:
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

4
在你的.kv文件中,你可以这样写:
#:import threading threading
.
.
.
    Button:
        on_release: threading.Thread(target=root.do_something).start()

请查看线程文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接