从ListAdapter中的按钮调用方法open_project时,我有以下代码导致AttributeError。
AttributeError:' AppScreenManager'对象没有属性' open_project'
如何从当前屏幕访问类HomeScreen中的open_project方法?
在main.py中我创建了应用程序:
from kivy.app import App
from manager import AppScreenManager
from startscreen import StartScreen
from kivy.core.window import Window
class PdesignerApp(App):
def build(self):
sm = AppScreenManager()
sm.add_widget(StartScreen())
return sm
if __name__ == "__main__":
PdesignerApp().run()
文件manager.py
from kivy.uix.screenmanager import ScreenManager
class AppScreenManager(ScreenManager):
pass
文件startscreen.py
from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
from kivy.clock import Clock
Builder.load_file('startscreen.kv')
class StartScreen(Screen):
def __init__(self, **kwargs):
super(StartScreen, self).__init__(**kwargs)
Clock.schedule_once(self.start, 1)
def start(self, *args):
if not self.manager.has_screen('HomeScreen'):
from homescreen import HomeScreen
self.manager.add_widget(HomeScreen())
self.manager.current = 'HomeScreen'
文件startscreen.kv
<StartScreen>:
name: 'StartScreen'
BoxLayout:
orientation: "vertical"
Image:
source: './images/splash-foto.jpg'
然后在homescreen.py文件中,我有以下相同序列的代码片段:
from kivy.uix.listview import ListItemButton
class ProjectButton(ListItemButton):
pass
class HomeScreen(Screen):
#and some definitions here etc.
def __init__(self, **kwargs):
super(HomeScreen, self).__init__(**kwargs)
#and a list of initialisations here
def open_project(self, project):
#and quite some processing code here
在homescreen.kv文件中,我有以下内容:
# File: homescreen.kv
#: import Factory kivy.factory.Factory
#: import homescreen homescreen
#: import ListAdapter kivy.adapters.listadapter.ListAdapter
<ProjectButton>:
background_normal: ''
background_down: './images/ProjList-sel.png'
on_release: app.root.open_project(self.text)
<HomeScreen>:
name: 'HomeScreen'
project_results_list: project_results_list
BoxLayout:
ListView:
id: project_results_list
adapter:
ListAdapter(data=[], args_converter=lambda row_index,
an_obj: {'text': an_obj,'size_hint_y': None,'height': 25},
cls=homescreen.ProjectButton)
答案 0 :(得分:0)
你的问题在homescreen.kv:
on_release: app.root.open_project(self.text)
它不起作用,因为app.root
是您的ScreenManager
,而不是您的HomeScreen
,因为它起作用,您需要在open_project
上引用HomeScreen
{1}},现在,我没有看到kv代码实现HomeScreen
,但你可以给它一个id,并使用app.root.ids.home_screen
,但还有另一种方法,因为ScreenManager
提供了一种按名称获取屏幕引用的方法。
on_release: app.root.get_screen('HomeScreen').open_project(self.text)