【问题标题】:Kivy and infinite thread loop - app freezesKivy 和无限线程循环 - 应用程序冻结
【发布时间】:2022-01-15 21:22:30
【问题描述】:

我必须将长任务分成线程。在 Kivy 应用程序的任意位置创建线程会使整个应用程序等待线程函数的结束,因此使用与不使用线程没有区别。我做错了什么?

kv 文件:

BoxLayout:
    Button:
        on_press: threading.Thread(target=app.test()).start()
    Button:
        on_press: app.press()

python 代码:

class MyApp(App):
    running = True

    def on_stop(self):
        self.running = False

    def test(self):
        while self.running:
            print('test')
            time.sleep(2)

    def press(self):
        print('press')

if __name__ == '__main__':
    MyApp().run()

单击按钮并创建线程后,应用程序将冻结。如何创建后台线程?

【问题讨论】:

    标签: python multithreading kivy


    【解决方案1】:

    Thread(target=app.test()) 立即调用app.test(),然后进入无限循环。目标是函数本身,而不是它的返回值。代码应如下所示(不带括号):

    threading.Thread(target=app.test).start()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多