python-3.x - Kivy中如何防止widget的大小改变?

标签 python-3.x widget size kivy python-3.4

我一直在玩this代码,我发现了一些(可能)奇怪的事情:当我将父级添加到我的类中时,大小更改为 [100, 100] (参见注释):

from random import random, randint

import kivy

kivy.require('1.8.0')

from kivy.config import Config

Config.set('graphics', 'fullscreen', '0')

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Line, Ellipse, Triangle, Rectangle


class MyPaintWidget(Widget):
    def on_touch_down(self, touch):
        with self.canvas:
            Color(random(), 1, 1, mode='hsv')
            touch.ud['line'] = Line(points=(self.width - touch.x, self.height - touch.y))
            print(self.width, self.height)  # It works OK if I return painter below, but it's not if I return parent.

    def on_touch_move(self, touch):
        touch.ud['line'].points += [self.width - touch.x, self.height - touch.y]


class Example(App):
    def build(self):
        parent = Widget()
        painter = MyPaintWidget()
        print(painter.size)  # Shows [100, 100] anyway.
        parent.add_widget(painter)
        return parent  # If I return painter, everything works as I want (except painter.size still shows [100, 100]).


if __name__ == '__main__':
    Example().run()

为什么会发生这种情况?我应该怎样做才对呢?

最佳答案

(100, 100) 是小部件的默认大小。在这种情况下,您的画家具有该尺寸,因为您从未将其设置为其他任何东西。

即使它的父级是一个会自动移动绘制器并调整其大小的布局类,此时它的大小仍会显示为 (100, 100),因为布局还没有时间运行。此时您通常不应该担心像素值 - 如果您需要其他东西来依赖它们,请使用绑定(bind)在第一个值更改时自动更新其他值。 kv 语言使这变得特别容易。

关于python-3.x - Kivy中如何防止widget的大小改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24769309/

相关文章:

css - div 容器大小问题

python - 在 Python 2 下运行脚本时如何忽略 Python 3 语法?

python - CSV 循环遍历行

button - Matplotlib 按钮

android - 如何通过 Intent 将数据从小部件配置类传递到小部件提供程序类?

android - 当我切换 Activity 时,RadioGroup 成员按钮不断更改 ID

javascript - Svg 背景之间的水平线

python - 如何以适用于 py2 和 py3 的方式在 Python 中定义二进制字符串?

python-3.x - 如何检查连接到 GRPC 服务器的客户端

c - 32位环境下c中指针的大小