如何在 Kivy 中获取小部件/布局的实际大小? [英] How can I get widget's/layout's actual size in Kivy?

查看:54
本文介绍了如何在 Kivy 中获取小部件/布局的实际大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 BoxLayout 中有这个布局(以及其他元素):

I have this layout inside BoxLayout (along with another elements):

<PlayField>:
    size_hint_x: None
    width: self.height
    canvas.before:
        Color:
            rgb: .9, .9, .9
        Rectangle:
            pos: self.pos
            size: self.size

main.py:

class PlayField(Layout):  # Or should it be Widget?
    pass

我如何获得它的实际尺寸?print(self.size) 显示默认大小 (100, 100),虽然它不是真的.

How do I get actual size of it? print(self.size) shows default size (100, 100), although it's not true.

推荐答案

小部件的大小取决于您检查的时间.大小不是在创建小部件时计算的,而是在放置在布局中时计算的.例如:

Size of widget depends on when you're checking. Size isn't calculated when widget is created but when it's placed inside Layout. For example:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.layout import Layout

kv = '''
<Foo>:
    on_touch_down: print(self.size)
'''
Builder.load_string(kv)

class Foo(Layout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        print (self.size)

class MyApp(App):
    def build(self):
        return Foo()

MyApp().run()

__init__() 方法内部的size 值仍然是(100, 100).稍后点击小部件,放置后,将返回正确的值.

Inside __init__() method value of size is still (100, 100). Clicking on widget later, after it's been placed, will return proper value.

如果你愿意,你可以将widget size绑定到一个方法上,在resize之后会调用这个方法:

If you want, you can bind widget size to a method, which will be called after resizing:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.layout import Layout

class Foo(Layout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.bind(pos=self.update)
        self.bind(size=self.update)
        self.update()

    def update(self, *args):
        print(self.size)
        self.canvas.clear() 
        with self.canvas:
            pass

class MyApp(App):
    def build(self):
        return Foo()

MyApp().run()

首先,Foo 是使用默认大小值创建的.然后它被显示出来,因此计算出适当的尺寸值并将其分配给 size 属性,这会触发 update 方法.任何其他大小更新(例如,如果您重新缩放窗口)也将触发此方法.Kivy 语言 会自动执行此操作,这是推荐的方法.

First, Foo is created with default size value. Then it's displayed, so proper size value is calculated and assigned to size property, which triggers update method. Any other updating of size (for example if you rescale window) will also triger this method. Kivy language does this automathically and it's recommended method.

最后,我不知道你想要达到什么目的,但我怀疑你并不真正需要这个值.

Lastly, I don't know what you're trying to achieve but I suspect you don't really need this value right away.

这篇关于如何在 Kivy 中获取小部件/布局的实际大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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