访问“高度"小部件实例的属性 [英] Accessing "height" property of an instance of a widget
问题描述
创建小部件后,我需要访问其高度.但是,每当我尝试访问my_widget.height
时,它都会返回默认高度100
而不是实际高度.
I need to access the height of a widget after it is created. However, whenever I tried to access my_widget.height
, it returns the default height of 100
rather than the actual height.
可以在my_widget
类的on_touch_down
定义内检索self.height
.
Retrieving self.height
inside the on_touch_down
definition of the my_widget
class works though.
我的问题确实在以下代码中得到了最好的描述.
My problem is really best described in the following code.
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网站上的指南,但找不到我想念的东西.
I spent hours reading different parts of the API doc and the guides on the Kivy website, but couldn't quite find what I missed.
推荐答案
在build()方法中,尚未构建应用程序,因此小部件具有其默认值,因此您必须稍后获取该信息.有以下选项:
In the build() method the application has not yet been built so the widget has its default value, so you must obtain that information a moment later, for this there are the following options:
- 使用
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()
这篇关于访问“高度"小部件实例的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!