访问“高度"小部件实例的属性 [英] Accessing "height" property of an instance of a widget

查看:47
本文介绍了访问“高度"小部件实例的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建小部件后,我需要访问其高度.但是,每当我尝试访问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:

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()

  • 使用 Clock.schedule_once() :
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆