python - 访问小部件实例的 "height"属性

标签 python kivy

我需要在创建小部件后访问其高度。但是,每当我尝试访问 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() 方法中,应用程序尚未构建,因此小部件具有其默认值,因此您必须稍后获取该信息,为此有以下选项:

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/

相关文章:

python - 计算 numpy 数组(图像)特定部分的平均值

python - 如何从 python 脚本中控制 Windows shell 窗口的大小?

python - Kivy 复选框在 ScrollView 中不起作用

python - Kivy,如何在 Canvas 中使用数据

python : Count dynamic row

python - 从字符串中删除特定的控制字符 (\n\r\t)

python - 如何下载文件并将其传递给函数

python - TensorFlow:如何通过权重变量对批量张量进行批处理?

python - 在基维上课时播放/停止音乐

python-3.x - 系统退出 : 1 Error on using kivy