本文介绍了如何在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__()方法大小的值仍为(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.

如果需要,可以将窗口小部件大小绑定到一个方法,该方法将在调整大小后调用:

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方法.尺寸的任何其他更新(例如,如果您重新缩放窗口)也将触发此方法. 基辅语言自动执行此操作,因此建议使用此方法.

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中获取小部件/布局的实际大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 15:41