我正在努力同时运行我的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
,并且parent_main立即运行
4。如果我仅从“ run()”中删除括号,那么它将变成“ run”。我得到Segmentation fault (core dumped)
答案 0 :(得分:1)
您需要在主线程上运行App
。我建议像这样:
def start_father_main(dt):
Thread(target = Client.father_main).start() #Client is locally imported
if __name__ == '__main__':
Clock.schedule_once(start_father_main, 10)
Sound().run()
我还没有测试过这段代码,但是它应该可以给您带来启发。
答案 1 :(得分:1)
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()