【发布时间】:2017-02-07 20:03:39
【问题描述】:
我正在处理两个文件
- test.py
- test.kv
test.py的内容如下:
import kivy
kivy.require('1.0.0')
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
Builder.load_file("test.kv")
class MainScreen(Screen):
def __init__(self, *args, **kwargs):
super(MainScreen, self).__init__(*args, **kwargs)
def printIds(self):
print self.ids
def printChildren(self):
print self.ids.box.children
for child in self.ids.box.children:
print child.text, child.id
def addButton(self):
self.ids.box.add_widget(Button(text = "newly added Button", id = "test_button_id"))
pass
class MyApp(App):
def __init__(self,*args, **kwargs):
super(MyApp, self).__init__(*args, **kwargs)
def build(self):
app = MainScreen()
return app
if __name__ == '__main__':
MyApp().run()
test.kv的内容是:
<MainScreen>:
BoxLayout:
orientation: "horizontal"
id: box
Label:
text: "test label"
id: test_label_id
Button:
text: "Print Children"
on_release: root.printChildren()
Button:
text: "Print ids"
on_release: root.printIds()
Button:
text: "Add Button"
on_release: root.addButton()
我的问题如下: 我想通过 python 文件中的 self.ids 命令访问新添加的按钮(将在通过按下按钮添加按钮调用函数 addButton 时添加)。但是当我这样做时(即按下按钮打印 ids)它只显示我在 kivy 文件中分配的 ids,即:box(这是 BoxLayout 的 id)和 test_label_id(这是测试标签的 id )。
我想错了吗?我的意思是,如果我使用self.ids.box.add_widged(Button(text="...", id="...")) 命令在python 文件中添加一个按钮,它应该可以通过self.ids 命令看到,对吧?
我也可以在另一个方向上进行测试:如果我打印boxlayout 的所有孩子并抓住他们的例如使用命令child.text 或child.id 的文本和ID 它会显示我新添加的按钮的文本和ID,以及其他按钮/标签的文本,但不是我在kivy 文件中分配的ID(特别是:它为他们显示无)。
我是不是做错了什么?
【问题讨论】: