我一直在玩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/