我需要在创建小部件后访问其高度。但是,每当我尝试访问 my_widget.height
时,它都会返回默认高度 100
而不是实际高度。
在 my_widget
类的 on_touch_down
定义中检索 self.height
是可行的。
下面的代码确实最好地描述了我的问题。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class Layout(BoxLayout):
# the following yields the correct height of Layout,
# which is the same as the height of the Window
def on_touch_down(self, touch):
print("inside Layout via on_touch_down:", self.height)
class MyApp(App):
def build(self):
l = Layout()
# However, accessing the height here yields the
# the default height 100
print("inside MyApp:", l.height)
return l
if __name__ == "__main__":
MyApp().run()
我花了几个小时阅读 API 文档的不同部分和 Kivy 网站上的指南,但找不到我错过的内容。
最佳答案
在 build() 方法中,应用程序尚未构建,因此小部件具有其默认值,因此您必须稍后获取该信息,为此有以下选项:
- 使用
App.on_start()
:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class Layout(BoxLayout):
pass
class MyApp(App):
def build(self):
l = Layout()
return l
def on_start(self):
print(self.root.height)
if __name__ == "__main__":
MyApp().run()
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
class Layout(BoxLayout):
pass
class MyApp(App):
def build(self):
l = Layout()
Clock.schedule_once(self.after_build)
return l
def after_build(self, dt):
print(self.root.height)
if __name__ == "__main__":
MyApp().run()
关于python - 访问小部件实例的 "height"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57541856/