Reputation: 23766
I'm really new to Kivy and I'm trying to position some text on a canvas, but I found that the Label
I'm using isn't positioned properly. If I'm drawing a Rectangle
with the same values it has the right position.
I found some similar questions here but I think there was no answer for me.
Here's my code:
class MyClass(Widget):
def __init__(self, **kwargs):
super(MyClass, self).__init__(**kwargs)
self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
self._keyboard.bind(on_key_down=self._on_keyboard_down)
def _keyboard_closed(self):
pass
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
with self.canvas:
lbl_staticText = Label(font_size=12)
lbl_staticText.text = 'This is some nice random text\nwith linebreak'
lbl_staticText.texture_update()
textSize = lbl_staticText.texture_size
Rectangle(pos=(1024/2 - textSize[0]/2, 600), size=(textSize[0], textSize[1])); #Rectangle with same position and same size
lbl_staticText.pos = (1024/2 - textSize[0]/2, 600)
The result looks like:
As you can see the Rectangle
position is horizontally centered as expected but the Label
is neither centered nor has the right height position.
Please can you tell me why there is a difference?
Thanks!
Upvotes: 1
Views: 729
Reputation: 12199
Well, you forgot to check for the size of the label that's first of all. The default one is always [100, 100]
. You didn't add the Label
anywhere as a child, therefore it ignores size_hint
which is by default set to [1, 1]
.
The end result:
Label
widget area is [100, 100]
Label
texture is [something, something]
(for me that's [160, 32]
)Now you create a Rectangle
with size of the Label
's texture size and place it somewhere, then you move the Label
to align it. Their sizes are different.
Uncomment the last commented line to see the difference.
class MyClass(Widget):
...
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
with self.canvas:
lbl_staticText = Label(font_size=12)
lbl_staticText.text = 'This is some nice random text\nwith linebreak'
lbl_staticText.texture_update()
textSize = lbl_staticText.texture_size
Color(1, 0, 0, 1)
Rectangle(
pos=(100+textSize[0]/2.0, 100),
size=(textSize[0], textSize[1])
)
lbl_staticText.pos = (100+textSize[0]/2.0, 300)
print(lbl_staticText.size, textSize, lbl_staticText.size == textSize)
#lbl_staticText.size=(textSize[0], textSize[1]) # this!
Color(0, 1, 0, 1)
Rectangle(
pos=lbl_staticText.pos,
size=lbl_staticText.size
)
runTouchApp(MyClass())
Upvotes: 1