我想向 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:“super”对象没有属性“getattr”
最佳答案
问题 - 属性错误
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
。
解决方案
解决方案有两个选项。
选项 1 - 使用 get_screen()
在此选项中,我们使用 get_screen()
检索实例化对象 MainScreen:
函数,以便我们可以访问它的方法或属性,例如id:abc
。我们将进行以下改进:
kv 文件:
- 我们 name屏幕,
name: 'MainScreen'
和name: 'SecondScreen'
对于实例化对象,MainScreen:
和SecondScreen:
> 分别。
片段 - kv 文件
ScreenManagement:
transition: SwapTransition()
MainScreen:
name: 'MainScreen'
SecondScreen:
name: 'SecondScreen'
Py 文件
- 使用
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])
选项 2 - 使用 id:主屏幕
在此选项中,我们将 id: mainscreen
添加到实例化对象 MainScreen:
并使用 ids.mainscreen
访问其方法) 或属性,例如id:abc
。我们将进行以下改进:
kv 文件:
- 将
id: mainscreen
添加到实例化对象,MainScreen:
片段 - kv 文件
ScreenManagement:
transition: SwapTransition()
MainScreen:
id: mainscreen
SecondScreen:
Py 文件
- 将
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])
关于python - 如何在 Kivy 中通过 ids 正确链接按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217002/