首页 > 解决方案 > 如何使用kivy一次运行两个进程

问题描述

我正在努力同时运行我的 Kivy 应用程序和本地导入的 python 脚本。

完整的python代码

import Client # Locall import
import time
from threading import Thread
from kivy.app import App
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen

class MainWindow(Screen):
    pass

class SecondWindow(Screen):
    pass

class WindowManager(ScreenManager):#will manage navigation of windows       
    pass

kv = Builder.load_file("my.kv")

class Sound(App):
    def build(self):
        return kv
    def ipconfig(self,input_ip):
        if len(input_ip) == 13:
            print('Address binded!!')
            Client.host = input_ip #Modify ip adress
        else:
            print('Invalid input_ip')```

if __name__ == '__main__':
    #Sound().run()#Kivy run method
    Thread(target = Sound().run()).start()
    time.sleep(10)
    Thread(target = Client.father_main).start()

线程发生的地方

if __name__ == '__main__':
    #Sound().run()#Kivy run method
    Thread(target = Sound().run()).start()
    time.sleep(10)
    Thread(target = Client.father_main).start() #Client is locally imported

问题

1.只有kivy应用程序运行,但father_main函数失败。

2.father_main 运行的唯一时间是我关闭 kivy 应用程序时。

3.如果我尝试从 Sound() 中删除“run()”。我得到TypeError: 'Sound' object is not callable,father_main 立即运行

4.如果我只从'run()'中删除括号,它就会变成'run'。我明白了Segmentation fault (core dumped)

标签: python-3.xlinuxmultithreadingkivy

解决方案


kivy 不鼓励使用 time.sleep ()并且我仍然不知道您的程序到底是什么,但这里有一个解决方案。

创建一个on_start方法(在 kivy 应用程序启动时运行的方法)并从那里添加启动 ipconfig 方法,但您将异步启动它。

from multiprocessing.pool import ThreadPool


class Sound(App):
    def on_start(self):
        pool = ThreadPool(processes=1)
        async_start = pool.apply_async(self.ip_config, ("value for ip_input here"))
        # do some other things inside the main thread here

if __name__ == "__main__":
    Sound().run()


推荐阅读