我还是 kivy 的新手,我似乎无法在其他地方找到我的案例。我想从主应用程序类访问屏幕类中的方法:
class MainGUI(Screen):
d_travelled = StringProperty()
def update_distance(self,dt):
self.d_travelled = dt
class SecondaryGUI(Screen):
pass
class GUIManager(ScreenManager):
pass
class WindowGUI(App):
def __init__(self):
super().__init__()
self.odrive = myDrive.Motors()
threading.Thread(target = self.RobotControl).start()
def build(self):
self.title = 'MyTitle'
kv = all_imports.Builder.load_file('kv_styles/robot_3.kv')# which instantiate the GUIs
return kv
def RobotControl(self):
while True:
self.root.update_distance(self.odrive.encoder_cal()) <-----Error
我在 WindowGUI
中有我的机器人指令,需要与 kivy 并排运行。首先,我想在我的 MainGUI 上显示编码器读数。但是 self.root
中的 RobotControl
指的是 GUIManager
。当然,这会引发错误。我如何在 MainGUI
中引用 RobotControl
?是否可以将 def update_distance(self,dt)
放入 GUIManager
并让 MainGUI
显示编码器读数?如果是这样,如何?
我的 kv 文件:
#:kivy 2.0
#:import utils kivy.utils
GUIManager:
MainGUI:
SecondaryGUI:
<MainGUI>:
name: "main"
BoxLayout:
orientation: "horizontal"
size: root.width, root.height #covers entire window
padding: 15
GridLayout:
cols: 1
spacing: 10
size_hint_x: 0.4
# padding_right: 50
BoxLayout:
orientation:"horizontal"
size_hint: 1,.4
Label:
text: "Drop Distance"
size_hint: .75,0.1
Button:
id: zero_drop
text: "Zero"
size_hint: .25,.1
on_press:app.odrive.zero_encoder_read()
BoxLayout:
orientation: "horizontal"
TextInput:
id: Encoder
multiline: False
readonly: True
text: root.d_travelled <-------I want to display it here
size_hint_x: 0.75
答案 0 :(得分:0)
感谢 el3phanten 来自 kivy discord 频道。这就是我解决问题的方法:
from kivy.clock import mainthread
class MainGUI(Screen):
# Do something
class SecondaryGUI(Screen):
pass
class GUIManager(ScreenManager):
pass
class WindowGUI(App):
d_travelled = StringProperty()
def __init__(self):
super().__init__()
self.odrive = myDrive.Motors()
threading.Thread(target = self.RobotControl).start()
def build(self):
self.title = 'MyTitle'
kv = all_imports.Builder.load_file('kv_styles/robot_3.kv')
return kv
def RobotControl(self):
while True:
val = self.odrive.encoder_cal()
self.set_val(val)
@mainthread
def set_val(self, val) :
self.d_travelled = val
和kv:
BoxLayout:
orientation: "horizontal"
TextInput:
id: Encoder
multiline: False
readonly: True
text: app.d_travelled
size_hint_x: 0.75