Kivy Screen Manager参考语言(KV语言) [英] Kivy Screen manager reference in kv language
问题描述
我正在尝试创建一个主菜单,该菜单使我可以在单击按钮时切换屏幕,但是我不知道如何从该按钮引用管理器.
I'm trying to make a main menu that lets me switch Screens when I click a button, but I can't figure out how to reference the manager from the button.
我有一个用于主菜单页面的设置(在kv文件中):
I have a setup for a main menu page (in kv file):
<MainMenu>: #AnchorLayout
BoxLayout:
Button:
text: "button 1"
Button:
text: "change screen"
on_release: root.manager.current = "OtherPage"
<MainWidget>:
screen_manger: screen_manager
ScreenManger:
id: screen_manger
Screen:
name: "MainMenu"
MainMenu
Screen:
name: "OtherPage"
OtherPage #this is defined in the kv file, just lazy to type it.
当我点击按钮Change Screen
时,我得到:
When I click on the Button Change Screen
, i get:
AttributeError: 'MainMenu' object has no attribute 'manager'
说实话,这并不令我惊讶.我想我可以通过以下方式解决此问题:在python代码中编写所有布局,并在BoxLayout
或MainMenu
小部件中添加对屏幕管理器的引用,但是我不知道如何在kv文件中执行此操作.>
which, in all honesty doesn't supprise me. I figure I can work around this by writing all the layout in python code and adding a reference to the screen manager in the BoxLayout
or MainMenu
widgets, but I have no idea how to do this in the kv file.
推荐答案
在更好地理解问题后重新做答案:
Re-doing the answer after understanding the issue better:
您的MainWidget实例不知道screen_manager引用,它不会传递给它(并且在其规则root
中引用MainWidget实例,而不是ScreenManager
实例.
Your MainWidget instance doesn't know about the screen_manager reference, it's not passed to it (and in its rule root
refer to the MainWidget instance, not the ScreenManager
one.
如果将manager: screen_manager
放在MainWidget
实例的声明下(第15行),并将manager
ObjectProperty添加到MainWidget的python声明中,则绑定将起作用.
If you put manager: screen_manager
under the declaration of MainWidget
instance (line 15), and you add a manager
ObjectProperty to the python declaration of MainWidget, then your binding will work.
python:
class MainWidget(Widget):
manager = ObjectProperty(None)
kv:
<MainWidget>:
screen_manger: screen_manager
ScreenManger:
id: screen_manger
Screen:
name: "MainMenu"
MainMenu:
manager: screen_manager
Screen:
name: "OtherPage"
然后它应该可以按您想要的方式工作.
then it should work as you want it.
此外,qua-non的此Wiki条目可能很有帮助 https://github.com/kivy/kivy/wiki/Linking-ScreenManager-to-a-different-Widget
edit: also, this wiki entry by qua-non could be helpful https://github.com/kivy/kivy/wiki/Linking-ScreenManager-to-a-different-Widget
这篇关于Kivy Screen Manager参考语言(KV语言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!