Kivy多Screen场景下调用Python函数报错的问题求助
问题解决:Kivy多Screen应用中调用函数的错误处理
错误原因分析
- 使用
app.root.text_wait()报错:app.root指向的是ScreenManager对象,而text_wait方法定义在MainApp类中,ScreenManager没有该方法,因此触发属性错误。 - 使用
root.text_wait()报错:root指向的是FirstScreen实例,这个类未定义text_wait方法,同样会触发属性错误。
解决方案
直接通过app调用MainApp中的text_wait方法即可——kv语言里的app直接指代当前运行的MainApp实例,而text_wait是它的成员方法。
修改kv文件中按钮的on_release语句:
on_release: app.text_wait("burger")
修改后的完整kv代码示例
<FirstScreen>: canvas: Color: rgb: (255/255, 170/255, 235/255) Rectangle: pos: self.pos size: self.size Line: width: 2 rectangle: self.x, self.y, self.width, self.height Button: id: obama_text size_hint: (.274, .2) pos_hint: {"x":.067, "y":.049} background_normal: '' background_color: 1, .5, .6, .85 font_size: 50 bold: True color: 200/255, 0/255, 70/255, 1 text: "OBAMA" on_release: app.text_wait("burger") # 修正后的调用方式 <SecondScreen>: FloatLayout: Button: text: "Go to third" pos_hint: {"center_x": .5, "center_y": .5} size_hint: .2, .2 on_release: root.manager.current = "third" <ThirdScreen>: FloatLayout: Button: text: "go to fourth" size_hint: .3, .1 pos_hint: {"x": .3, "y": .5} on_release: root.manager.current = "fourth" <FourthScreen>: FloatLayout: Button: text: "go to first" size_hint: .3, .1 pos_hint: {"x": .3, "y": .5} on_release: root.manager.current = "first"
补充说明
如果后续需要将text_wait方法放到特定Screen类中(比如FirstScreen),可以修改对应Screen类添加方法,之后用root.text_wait()调用:
class FirstScreen(Screen): def text_wait(self, text): # 编写方法逻辑 pass
这种情况下kv中的on_release: root.text_wait("burger")即可正常工作。
内容的提问来源于stack exchange,提问作者Courtney G
相关产品推荐
相关产品推荐

