我想在boxlayout中添加按钮,但是我的代码中存在一些问题。当我单击添加按钮或删除按钮时,我收到AttributeError消息。 感谢您的帮助。
我的python代码:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen, ScreenManager
class MainScreen(Screen):
pass
class SecondScreen(Screen):
pass
class ScreenManagement(ScreenManager):
pass
class TestApp(App):
def build(self):
self.title = 'Hello'
def add_more(self):
print('test')
addbutton = self.root.ids.abc
addbutton.add_widget(Button(text='hello'))
def remove(self):
print('test')
if len(self.root.ids.abc.children) > 0:
self.root.ids.abc.remove_widget(self.root.ids.abc.children[0])
if __name__=='__main__':
TestApp().run()
我的kv代码:
#: import SwapTransition kivy.uix.screenmanager.SwapTransition
ScreenManagement:
transition: SwapTransition()
MainScreen:
SecondScreen:
<MainScreen>:
BoxLayout:
id:aaa
Button:
text: 'Add'
on_press: app.add_more()
Button:
text:'Remove'
on_press: app.remove()
BoxLayout:
id:abc
<SecondScreen>:
AttributeError:“超级”对象没有属性“ getattr ”
答案 0 :(得分:2)
addbutton = self.root.ids.abc
File "kivy/properties.pyx", line 843, in kivy.properties.ObservableDict.__getattr__
AttributeError: 'super' object has no attribute '__getattr__'
根id: abc
中没有ScreenManager
。
解决方案有两个选择。
在此选项中,我们使用get_screen()
函数检索实例化的对象MainScreen:
,以便我们可以访问其方法或属性,例如id: abc
。我们将进行以下增强:
name: 'MainScreen'
和name: 'SecondScreen'
分别用于实例化对象MainScreen:
和SecondScreen:
。摘要-kv文件
ScreenManagement:
transition: SwapTransition()
MainScreen:
name: 'MainScreen'
SecondScreen:
name: 'SecondScreen'
get_screen()
函数检索实例化对象MainScreen
摘要-Py文件
def add_more(self):
print('test')
addbutton = self.root.get_screen('MainScreen').ids.abc
addbutton.add_widget(Button(text='hello'))
def remove(self):
print('test')
container = self.root.get_screen('MainScreen').ids.abc
if len(container.children) > 0:
container.remove_widget(container.children[0])
在此选项中,我们将id: mainscreen
添加到实例化对象MainScreen:
中,并使用ids.mainscreen
访问其方法或属性,例如id: abc
。我们将进行以下增强:
id: mainscreen
添加到实例化对象MainScreen:
摘要-kv文件
ScreenManagement:
transition: SwapTransition()
MainScreen:
id: mainscreen
SecondScreen:
self.root.ids.abc
替换为self.root.ids.mainscreen.ids.abc
摘要-Py文件
def add_more(self):
print('test')
addbutton = self.root.ids.mainscreen.ids.abc
addbutton.add_widget(Button(text='hello'))
def remove(self):
print('test')
container = self.root.ids.mainscreen.ids.abc
if len(container.children) > 0:
container.remove_widget(container.children[0])