問題描述
我正在嘗試制作一個主菜單,讓我在單擊按鈕時切換屏幕,但我不知道如何從按鈕中引用管理器.
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 添加到 pythonMainWidget 的聲明,那么您的綁定將起作用.
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.
蟒蛇:
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
這篇關于kv 語言中的 Kivy 屏幕管理器參考的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!